PDA

View Full Version : popen call to grep




farmerdoug
Jun 11, 2012, 05:17 PM
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.



mfram
Jun 11, 2012, 06:15 PM
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
Jun 11, 2012, 06:21 PM
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.

kakusan
Jun 11, 2012, 10:02 PM
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 }'

Mac_Max
Jun 11, 2012, 11:14 PM
If you don't mind learning (the basics of) a programming language in the process, perl has native language level support for grep.

http://perldoc.perl.org/functions/grep.html

robvas
Jun 12, 2012, 08:51 AM
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
Jun 12, 2012, 11:01 AM
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.

lee1210
Jun 12, 2012, 01:37 PM
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