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!
No comments:
Post a Comment
Thanks for the comment and for peeping into my blogspot. Hope you enjoy your reading them.
If you wish to receive posts updates, you can subscribe directly from this link:
http://feeds.feedburner.com/VertitosBlogspot
using any RSS reader or even Google Reader.
Again, appreciate your site visits.
Cheers then
VeRTiTO
Email: vertito@gmail.com