Link to home
Start Free TrialLog in
Avatar of khoty
khoty

asked on

grep in shell

I have a file in the following format:

Name
DOB
Address

sometimes the DOB is missing so I may only have

Name
Address

eg .
Name    Terry Likos
DOB     7/2/1971
Address 12 Grose street etc
Name   John Doe
Address 134 Grose street etc

so if I want to do a grep for 'Grose' then I want to get the
name and DOB(if there is any) and that person's address.
Is there a way to do this in a shell script? (my name and address file is almost 12MB so I want to do it fast)
Avatar of khoty
khoty

ASKER

There is one more little thing...
if I type 'Terry' and 'John' then I want to see if they live in the same street, as in the above example 'Grose street'.
So basically we want find all those people that live in a particular street either searching by street name , or searching by names. However the format of the result(s) returned will be the same ie.name and DOB(if there is any) and that person's address.
Not with grep!  Maybe with awk.  Take a look at "man awk" to see if it will do what you want.
awk '/^Name/{n=$0}/DOB{d=$0}/Address/{a=$0}/Grose/{print n; print d; print a; exit}' your_file
Avatar of ozo
I don't think that awk script is quite right.
Consider the a file like:

Name    Terry Likos
DOB     7/2/1971
Address 12 Rose street etc
Name   John Doe
Address 134 Grose street etc

Also, consider what would happen if you searched for /John/
Avatar of khoty

ASKER

awk '/^Name/{n=$0}/DOB{d=$0}/Address/{a=$0}/Grose/{print n; print d; print a; exit}' temp
awk: syntax error near line 1
awk: bailing out near line 1

There is ALSO one more little thing...
if I type 'Terry' and 'John' then I want to see if they live in the same street, as in the above example 'Grose street'.
So basically we want find all those people that live in a particular street either searching by street name , or searching by names. However the format of the result(s) returned will be the same ie.name and DOB(if there is any) and that person's address.

I think ahoffmann meant to type
awk '/^Name/{n=$0}/DOB/{d=$0}/Address/{a=$0}/Grose/{print n; print d; print a; exit}'
Although that still has the minor problem mentioned earlier.


awk 'BEGIN{ORS=";"}/^Name/{printf "\n"}{print}' your_file | egrep 'Terry|John' | tr ';' '\012'
Avatar of khoty

ASKER

how can I optimise awk 'BEGIN{ORS=";"}/^Name/{printf "\n"}{print}' your_file | egrep 'Terry|John' | tr ';' '\012'
this one is good...but runs very slow when I test it with a 12MB data file.
Avatar of khoty

ASKER

Adjusted points to 400
Avatar of khoty

ASKER

Adjusted points to 800
ASKER CERTIFIED SOLUTION
Avatar of ahoffmann
ahoffmann
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial