Saturday, July 10, 2010

Finding First Instance of the Pattern Using Grep in Linux

Grep in Linux
Have you ever faced a problem grepping (Parsing) for a pattern from a file, Definately being a Linux Administrator you have done it several times but have you came across a situation where from a huge file you only have to parse the first instance of the pattern, grepping the whole file for a pattern will be tedious and will be using more system resources especially when you are doing it using a script (Using Loop for, while, until)

The easy solution to tackle the problem is to use grep with inbuilt option which will display only the first instances instead of checking the whole file and than printing the first line using head command.


Command :
grep -m 1 "pattern" filename.txt


The "-m" option when passed with grep will search for the first matching pattern from the file and print the output same-way if you want to look for first 2 instances pass option "grep -m 2 "pattern" yourfilename.log"

Enjoy...

4 comments: