Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

farmerdoug

macrumors 6502a
Original poster
Sep 16, 2008
541
0
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

thanks.
 
Last edited:

mfram

Contributor
Jan 23, 2010
1,307
344
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.
 

farmerdoug

macrumors 6502a
Original poster
Sep 16, 2008
541
0
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.
 
Last edited:

kakusan

macrumors newbie
Jan 25, 2010
4
0
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;}'

or

awk '/pm EDT/ { getline; print; exit }'
 

robvas

macrumors 68040
Mar 29, 2009
3,240
629
USA
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

thanks.

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'
 

jared_kipe

macrumors 68030
Dec 8, 2003
2,967
1
Seattle
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'

Yeah that sounds way more efficient than a) opening the file yourself, b) using a language like awk to parse the file.
 
Last edited:

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
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.

-Lee
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.