1833780 Members
2474 Online
110063 Solutions
New Discussion

question on grep command

 
SOLVED
Go to solution
Narasimham
Advisor

question on grep command

I am working on HP-UX
I have a file as follows
Record 1
--------
Name:
address:
Phone:
Phone:
Record 2
--------
.

From the above in shell programming How do i grep for the first occurance of the string "phone:". Any body can help


Thanks
Narasimham
3 REPLIES 3
Darrell Allen
Honored Contributor
Solution

Re: question on grep command

Hi Narasimham,

If you only want the first occurance of "phone:" do:

grep "phone:" file | head -1

If "phone:" must be at the beginning of the line use "^phone:".

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)
A. Clay Stephenson
Acclaimed Contributor

Re: question on grep command

This is a little bit more complicated if what you really want, is the first 'Phone:' after each 'Name:'. If that is the case, then a little bit of Perl or Awk will be your best bet. Is this what you are really trying to do?

Regards, Clay
If it ain't broke, I can fix that.
H.Merijn Brand (procura
Honored Contributor

Re: question on grep command

1. With grep, you can also add '-i' for case-insensative searches Phone vs phone

2. To get the first Phone: from each /Record:/

perl -ne '/^Record\s+(\d+)/ and $rn=$1,next;$rn&&/^Phone/i or next;print;$rn=0;' datafile
Enjoy, Have FUN! H.Merijn