Operating System - HP-UX
1844276 Members
2444 Online
110230 Solutions
New Discussion

Re: grep and/or sed question

 
SOLVED
Go to solution
Jeff Picton
Regular Advisor

grep and/or sed question

Hello all

Can anyone tell me how I may grep or use sed to obtain the FIRST instance of a regular expression within a file ?

Jeff
7 REPLIES 7
Elmar P. Kolkman
Honored Contributor
Solution

Re: grep and/or sed question

Simplest way: grep | head -1

A lot of other solutions would work of course.
Every problem has at least one solution. Only some solutions are harder to find.
Mark Grant
Honored Contributor

Re: grep and/or sed question

Can we do perl?

perl -n -e 'if(/My Expression/){print;exit}' filename

Never preceed any demonstration with anything more predictive than "watch this"
Mark Grant
Honored Contributor

Re: grep and/or sed question

or awk if you like

awk 'match($0,"expression") > 0 {print;exit}
{next}' filename

I think, on large files, you would benefit from actually exiting when finding the first instance but maybe not.
Never preceed any demonstration with anything more predictive than "watch this"
Dietmar Konermann
Honored Contributor

Re: grep and/or sed question

Hmm... what avout this one?

sed -e '/My Expression/q;d'

Best regards...
Dietmar.
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)
Dietmar Konermann
Honored Contributor

Re: grep and/or sed question

Just saw that the bunny went to the grep/head solution, although that this is a really bad approach. Consider a file, several MBs large. Even if is there is a hit in the 1st line, grep will scan it completetly. You should not do that. :-)

Best regards...
Dietmar.
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)
Jeff Picton
Regular Advisor

Re: grep and/or sed question

Hi

Fortunately this log file is not large so the grep / head solution was fine for this purpose. Also the sed/awk solutions are fine but this is a shell script so didn't try the perl one.

Many Thanks

Jeff
Mark Grant
Honored Contributor

Re: grep and/or sed question

Hi Jeff,

Just for information, you can actually put the perl line in a shell script as it's a one liner and therefore much like putting awk or sed in your script.

On the other hand, it won't work too well if you don't actually have perl installed :)
Never preceed any demonstration with anything more predictive than "watch this"