Book Image

Troubleshooting CentOS

By : Jonathan Hobson
Book Image

Troubleshooting CentOS

By: Jonathan Hobson

Overview of this book

Table of Contents (17 chapters)
Troubleshooting CentOS
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using grep


Now let's consider the need to search the server's log files for specific keywords.

In this situation, you would use the command known as grep, which also becomes a very helpful technique to learn when you would like to perform an advanced string-based search of almost any file on your server.

Let's say you wanted to search for a specific e-mail address in the mail log file. To do this, you would use grep in the following way:

# grep "[email protected]" /var/log/maillog

Taking this one step further, grep can also be used to search in a recursive pattern across one or more files at the same time.

For example, in order to search the log file directory for an IP address (XXX.XXX.XXX.XXX), you would use the grep command in combination with the -R option like this:

# grep -R "XXX.XXX.XXX.XXX" /var/log/

Similarly, you can add line numbers to the output with the -n option like this:

# grep -Rn "XXX.XXX.XXX.XXX" /var/log/

Moreover, you will also notice that, during a multi-file based search, the filename is made available for each search result, but by employing the -h option, this can be disabled in the following way:

# grep -Rh "XXX.XXX.XXX.XXX" /var/log/

You can ignore case with the -i option in the following way:

# grep -Ri "XXX.XXX.XXX.XXX" /var/log/

Moving beyond this, grep can be used to sort the content of a search result by simply calling the sort command. An alphabetical sort order (a to z) can be achieved by simply adding sort at the end of your original command like this:

# grep -R "XXX.XXX.XXX.XXX" /var/log/ | sort 

A reverse alphabetical sort order (z to a) can be achieved by adding the -r option like this:

# grep -R "XXX.XXX.XXX.XXX" /var/log/ | sort -

And finally, if you wish to search for more than one value, you can invoke the –E argument like this (but do not include unnecessary white spaces between the pipes):

# grep -E "term 1|term 2|term 3" /var/log/messages

Of course, grep can do so much more, but for the purpose of troubleshooting, I would now like to draw your attention to one final, but very useful command. Known as diff, this command can be very useful in determining the differences between two files.