Author Topic: Any AWK or GREP Experts?  (Read 642 times)

Ben

  • Administrator
  • Senior Member
  • *****
  • Posts: 46,154
  • I'm an Extremist!
Any AWK or GREP Experts?
« on: October 12, 2006, 11:49:06 AM »
I haven't used either of these programs since college (and was pretty crummy with them back then), but I think one of them is what I need to do the following:

A coworker just did a project that required public comment. An NGO did the "form email" thing and 17,000 of its members sent him the same email. I've been asked if I can get the name and address info out of all the emails for import into a public comment database. The one component each of these emails has in common is that they contain name and address info as:

John Doe
123 Main St
Anytown, State, 12345
USA
johndoe@email.com

I can grab all the emails from my coworker's local Thunderbird inbox folder and dump them into a text file. I was thinking the easist thing to do would be to write an AWK or GREP command that would look for all instances of "USA", then also grab the three lines above that and send everything to a new file. I think I can grab the "USA" with 'grep USA myfile', but am too stupid to figure out how to also grab the three lines above. Specifying a space after every "USA" would be cool too.

Any help would be much appreciated.
"I'm a foolish old man that has been drawn into a wild goose chase by a harpy in trousers and a nincompoop."

BrokenPaw

  • friends
  • Senior Member
  • ***
  • Posts: 1,674
  • Sedit qvi timvit ne non svccederet.
    • ShadowGrove Interpath Ministry
Any AWK or GREP Experts?
« Reply #1 on: October 12, 2006, 12:07:14 PM »
cat foo.txt | grep "USA" -B 3 > bar.txt

or

cat foo.txt | grep "USA " -B 3 > bar.txt

If I understand you properly.
Seek out wisdom in books, rare manuscripts, and cryptic poems if you will, but seek it also in simple stones and fragile herbs and in the cries of wild birds. Listen to the song of the wind and the roar of water if you would discover magic, for it is here that the old secrets are still preserved.

Sindawe

  • friend
  • Senior Member
  • ***
  • Posts: 2,938
  • Vashneesht
Any AWK or GREP Experts?
« Reply #2 on: October 12, 2006, 01:34:40 PM »
Add the "-i" switch will tell grep to ignore case in the pattern being matched, in case some respondents did not capitalize USA

cat foo.txt | grep -i "USA" -B 3 > bar.txt
I am free, no matter what rules surround me. If I find them tolerable, I tolerate them; if I find them too obnoxious, I break them. I am free because I know that I alone am morally responsible for everything I do.

Ben

  • Administrator
  • Senior Member
  • *****
  • Posts: 46,154
  • I'm an Extremist!
Any AWK or GREP Experts?
« Reply #3 on: October 12, 2006, 02:47:56 PM »
Thanks guys -- I'll give this a try tomorrow AM!
"I'm a foolish old man that has been drawn into a wild goose chase by a harpy in trousers and a nincompoop."