如何在OSX中仅使用终端命令从两个文件中查找不常用的单词?

时间:2014-02-13 11:46:29

标签: macos unix terminal grep

我有两个四个字母的文件。

文件A包含四个字母单词的所有可能组合。 此文件中的单词,每行一个单词,排序如下:

aaaa 
aaab 
aaac
  .
  .
aaba
aabb

文件B包含“坏词”。这些也按排序顺序排列。文件B中的单词是文件A的子集。每个文件只有唯一的单词。给定文件中没有重复项。

什么是在文件A中仅查找“好词”并将其保存在终端的第二个文件中的有效方法? 我可以使用以下代码轻松编写Objective-C程序:

//Omitted file handling code. Passing in both the files words as arrays.
-(NSMutableArray)goodWords:(NSMutableArray*)allWords badWords:(NSMutableArray*)badWords
{
  int ap = 0; int bp=0;
  NSMutableIndexSet *indices = [[NSMutableIndexSet alloc]init];
  while(bp<badWords.count)
  {
     NSString* bs = [badWords objectAtIndex:bp];
     NSString* as = [allWords objectAtIndex:ap];
     if([as isEqualToString:bs])
     {
          //Make note of index containing bad word.
         [indices addIndex:ap];
         bp++; ap++; //Move both pointers ahead.
     }
     else
     {
       ap++; // Since both arrays are sorted, and the words don't match, I move the ap ahead. (since it is pointing at a "good word".
     }
  }
  //Make a copy of the original array of "good words".
  NSMutableArray *result = [NSMutableArray arrayWithArray:allWords];
  [result removeObjectsAtIndexes:indices]; //Remove the bad words.
  [indices release];
  return result; 
}

由于这些是单词列表,我不能使用GREP。有没有办法在OSX中只使用终端命令?我不知道从哪里开始使用unix / terminal命令。

编辑:修正了代码中的错误;
编辑:添加评论解释算法。
编辑:制作NSIndexSet NSMutableIndexSet;
编辑:意外键入AP而不是AllWords
编辑:修复泄漏。

1 个答案:

答案 0 :(得分:1)

这应该让你接近:

$ cat goodwords 
aaaa
aaab
aaac
aaad
aaae

$ cat badwords 
aaaa
aaad

$ comm -3 goodwords badwords | grep -v '^\t$'
aaab
aaac
aaae

grep就在那里,comm使用标签来分隔&#34;列&#34;)。

作为额外的奖励,您的Objective-C版本应该将值存储在NSSet中(因为没有欺骗),然后使用:

NSMutableSet *goodWords = [allWords mutableCopy];
[goodWords minusSet:badWords];