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 }'
Comments:

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 09:36 AM 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 09:56 AM IST #

this is shorter

sed -n '/line/{p;q;}' input.txt

Posted by nacho on March 16, 2008 at 12: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 16, 2008 at 07:55 PM IST #

Post a Comment:
  • HTML Syntax: NOT allowed
About

prasanna

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today