Wednesday, February 24, 2010

Search the first occurrence of a string or a pattern in a file and exit

When you want to search for the first occurence of a string in a file and exit, the below command may be useful, the file input.txt has the following contents,

Input file: input.txt

Start

Line: 1

Line: 2

Line: 3

Line: 4

Line: 5

End

To search for the first occurence of the word "Line:" from the above file and exit, use the below grep and awk combination,



cat input.txt grep "Line:" awk '{ print $2; exit }' (or) awk '/Line:/ { print $2;exit }' input.txt

No comments:

Post a Comment