Tuesday, April 30, 2013

Linux - Some useful applications of sed and grep

1) sed - how to find and replace within a file

This is one of the basic application of sed

sed -i 's/find-pattern/replace-pattern/g' filename



2) sed - How to search between two patterns:

sed -n '/start-pattern/,/end-pattern/p' filename

This is useful when you want to limit your search to a region within a file


e.g Between two time points

sed -n '/01:44:39/,/02:41:44/p' abc.log


3) sed - how to prefix/suffic something to the start/end of every line

You know this well if you are exposed to regular expression (makes way for some most powerful text manipulations).

^ - Denotes beginning
$ - Denotes ending

e.g Comment out some lines in a config file

sed -i 's/^/#/g' filename

e.g Add some comments to every line at the end

sed -i 's/$/<your text>/g' filename


4) grep multiple strings

grep 'warning\|error\|critical' /var/log/messages


5) grep and display few lines above the matched pattern

grep -A  2 'warning\|error\|critical' /var/log/messages


6) grep and display few lines below the matched pattern

grep -B  2 'warning\|error\|critical' /var/log/messages

No comments:

Post a Comment