Prasanna
- All
- Personal
- Sports
- Sun
- Tech
- Useful Code
Sunday Mar 16, 2008
Shell script: Matching the first occurrence of a string or a pattern in a file and exit
I was looking to solve the above problem, as lazy as ever googled for a solution, but couldn't find what I was looking for (though there were while loop solutions). If you need a single line shell script which matches the first occurrence of a string (or a pattern) from the input and exit, the following code could be useful.Input file: input.txt
Start
Line: 1
Line: 2
Line: 3
Line: 4
Line: 5
End
To get output 1 (second string in second line Line: 1) from the above file and exit, use the below grep and awk combination, although this may not be the efficient solution.
cat input.txt | grep "Line:" | awk '{ print $2; exit }'
Posted at 01:57PM Mar 16, 2008 by prasanna in Useful Code | Comments[4]


Two of the commands in your pipeline are unnecessary. First the "cat":
grep "Line:" input.txt | awk '{ print $2; exit }'
Second the "grep":
awk '/Line:/ { print $2;exit }' input.txt
Sorry but grep piped into awk is one of my pet peeves: http://blogs.sun.com/chrisg/entry/grep_piped_into_awk
Posted by Chris Gerhard on March 16, 2008 at 04:36 PM IST #
Hi Chris,
Thats fantastic, thanks a ton for pointing me that, I can update my code with the latest one.
Posted by Prasanna S on March 16, 2008 at 04:56 PM IST #
this is shorter
sed -n '/line/{p;q;}' input.txt
Posted by nacho on March 16, 2008 at 07:34 PM IST #
Thats another nice solution, so I need to come out of the grep world and do it using either awk or sed :)
Posted by Prasanna S on March 17, 2008 at 02:55 AM IST #