popen call to grep

Discussion in 'Mac Programming' started by farmerdoug, Jun 11, 2012.

  1. farmerdoug, Jun 11, 2012
    Last edited: Jun 11, 2012

    farmerdoug macrumors 6502a

    Sep 16, 2008
    I'd like to get the first line after a line containing "pm EDT".
    I've read the man pages for grep and googled but to no avail.
    Help appreciated.

    I'm using Xcode4 with OS 10.7.4

  2. mfram macrumors 65816

    Jan 23, 2010
    San Diego, CA USA
    You don't need grep at all. You can do this all within your program. Open the file, search until you find the string you're looking for... then take the next line after it.

    If you're using a scripting language, then I agree you would use grep. But if you're using a high-level language, then it's just slowing you down. And if you are using Objective-C, then you can use NSString convenience methods or maybe regular expressions to get the data you need.
  3. farmerdoug, Jun 11, 2012
    Last edited: Jun 11, 2012

    farmerdoug thread starter macrumors 6502a

    Sep 16, 2008
    I have to do this with a lot of files. It means opening them; reading them into a file; then searching. grep is much cleaner.
  4. kakusan macrumors newbie

    Jan 25, 2010
    I don't think you can do that with grep alone. You could use grep as part of a pipeline...

    In any case if you're insistent on using popen, I'd suggest sed or awk instead of grep. Something like:

    sed -n '/pm EDT/{n;p;q;}'


    awk '/pm EDT/ { getline; print; exit }'
  5. Mac_Max macrumors 6502

    Mar 8, 2004
  6. robvas macrumors 68030

    Mar 29, 2009
    Use two greps -

    grep -A1 'pm EDT' whateverfile

    That will get you the line you're looking for, AND the line after

    Then, use another grep to find lines that don't match 'pm EDT'

    grep -v 'pm EDT'

    Stick them all one one line with a pipe:

    grep -A1 'pm EDT' whateverfile | grep -v 'pm EDT'
  7. jared_kipe, Jun 12, 2012
    Last edited: Jun 12, 2012

    jared_kipe macrumors 68030


    Dec 8, 2003
    Yeah that sounds way more efficient than a) opening the file yourself, b) using a language like awk to parse the file.
  8. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    grep -A1 "pm EDT" file.txt | grep -v "pm EDT"

    Of course if two lines in a row have pm EDT you won't get the second line in your output. I can't write the awk on my phone, but that would be better. Set a flag when you see the pattern, output a line when it's set. Clear it if the new line doesn't contain the pattern.


Share This Page