Friday, September 14, 2007

print leading/trailing lines before/after a matching string

Usually all mail log files specially SendMail, Qmail and Postfix, generates multi-lines of mail log files into its default log file. That is, a message line is being dumped to a log file from the time of a client's connection up to client's disconnection, there are already several lines dumped to its default mail log file, say /var/log/maillog.

Now, say we want to print a few lines before and after a matching string is found, here's a quick way of accomplishing this task using grep.

Grep can display leading and trailing lines before a string match is found.

Here's a quick way to do it.

# cat testfile.txt
~~~~~~~~~~~~~~~~~~~~
123
456
678
Linux SysAd Blog
abc
def
ghi
~~~~~~~~~~~~~~~~~~~~

Now, let us try to print leading lines before a match to 'linux' string is found using grep.

# grep -B 2 Linux testfile.txt
output:
~~~~~~~~~~~~~~~~~~~~
456
678
Linux SysAd Blog
~~~~~~~~~~~~~~~~~~~~

The above comamnd displays 2 leading lines before the matched string.

Alternatively, let us print 2 trailing lines after a match is found. This can be done like so

# grep -A 2 Linux testfile.txt
Output:
~~~~~~~~~~~~~~~~~~~~
Linux SysAd Blog
abc
def
~~~~~~~~~~~~~~~~~~~~


As you can see, a specified number of trailing lines before the search string 'Linux' .


MORE GREP APPLICATION
~~~~~~~~~~~~~~~~~~~~~~

You can also apply this to commented text file. In a large commented config files, usually putting a marker string is helpful on editing large files. The above commands can be handy if you wish to view those trailing and leading lines before that marker string.

# cat testfile.cfg
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ..

# Two thousand config and commented lines before the next line
#
# here goes my marker string
# CHECK1
#
# here goes the actual config line
value1 = 1
value2 = 2
#
# another thousand config lines.

#
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Without using an editor, grep can easily display lines of value1 and value2 using CHECK1 as my string marker.

Final Note
~~~~~~~~~~

Grep saves time and effort on handling these type of grep searching.

HTH

Thanks for today's support!

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy