1

I've got an NSTask that uses a piped grep command; The output matches, and grep comes back with a match to my input string — although when comparing it back to the original string it doesn't match somehow. I'm probably not comparing the returned string properly against the other one? please help.

NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/path/to/file"];

NSTask *task;
        task = [[NSTask alloc] init];
        [task setLaunchPath: @"/usr/bin/grep"];

NSString *words = @"words";

NSArray *arguments;
        arguments = [NSArray arrayWithObjects: @"-o", "-a", "-m 1", @"-h", @"-r", words, filePath, nil];

        [task setArguments: arguments];

NSPipe *pipe;
        pipe = [NSPipe pipe];
        [task setStandardOutput: pipe];

NSFileHandle *file;
        file = [pipe fileHandleForReading];

        [task launch];

NSData *data;
        data = [file readDataToEndOfFile];

NSString *string;
        string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

NSLog (@"grep returned:\n%@", string);
NSLog (@"grep searched:\n%@", words);

    [task release];

if ([string isEqualToString:words]) {
    NSLog(@"match: %@", string);
} else {
    NSLog(@"failed");

    [string release];

It fails with the output in console looking like this:

grep returned:
words
grep searched:
words
failed
Joe Habadas
  • 628
  • 8
  • 21
  • Is `NSTask` a requirement? If I understand what you're doing, `NSScanner` should work. – FluffulousChimp Sep 11 '12 at 01:20
  • It would probably help, although if you have a good example of NSScanner I would love to see it, or know the advantage/disadvantage. thanks! – Joe Habadas Sep 11 '12 at 02:10
  • Not really relevant, but this `NSData *data; data = whatever` way of declaring variables is odd and makes your code take more space than it needs to. Why not just `NSData *data = whatever`? – Chuck Sep 11 '12 at 02:23
  • Yes, I know — do you really think it's eating up resources though, or taking up space? Probably not more than a few bytes. It's done that way just to make it easier to follow on here... – Joe Habadas Sep 11 '12 at 02:33

1 Answers1

2

I believe grep prints a newline after its output, so it would return "words\n" while your string is just "words".

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • @JoeHabadas After retrieving grep's output into `string` you could do this `string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]` before doing the comparison. Leading and trailing whitespace needs to be unimportant, obviously, and not present in the string you're comparing to (`words` in your example code.) – sjs Sep 11 '12 at 03:01