Grepping (and egrepping) with Style

Grep is a powerful tool. It can do many things well. It can also be used in conjunction with other tools. If you are new to grep, it is a supercharged search tool. The basic format of the command is:

grep [options] PATTERN [FILE…]

Many options are available and described in the man page, so I won’t go into them here. I will just list some of my favorite grep commands. (who am I kidding? I just want a place to copy them from when I am not at my own computer)

#This command searches for a string and includes the preceding 5 lines and the 5 lines that follow it and shows the line numbers as well.

grep -n -B5 -A5 searchstring /tmp/filename

#This command uses grep to traverse the output from a find command.
find . -exec grep searchstring {} \; -print

#This command allows you to output a sorted list of connections from the month of Mar 2013
grep Mar/2013 /var/log/apache2/access.log |  awk ‘{ print $1 }’ | sort -n | uniq -c | sort -rn | head

#Finding warnings and errors in your log
egrep -w ‘warning|error|critical’ /var/log/messages

About vicki

Welcome to the Sovereign Republic of Vickistan. I am the President here. Lucky me! No taxes or laws yet. Lucky you!
This entry was posted in Linux. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *