How to Search a text in file using Grep Command

Posted on 7:34 PM by Bharathvn

The grep command comes in handy when you need to perform more advanced string
searches in a file. In fact, the phrase to grep has actually entered the computer jargon as a verb, just as to Google has entered the popular language. Here are examples of the grep command:

$ grep francois myfile.txt Show lines containing francois
# grep 404 /var/log/httpd/access_log Show lines containing 404
$ ps auwx | grep init Show init lines from ps output
$ ps auwx | grep “\[*\]” Show bracketed commands
$ dmesg | grep “[ ]ata\|^ata” Show ata kernel device information

These command lines have some particular uses, beyond being examples of the grep
command. By searching access_log for 404 you can see requests to your web server
for pages that were not found (these could be someone fishing to exploit your system,
or a web page you moved or forgot to create). Displaying bracketed commands that are
output from the ps command is a way to see commands for which ps cannot display
options. The last command checks the kernel buffer ring for any ATA device information, such as hard disks and CD-ROM drives.

The grep command can also recursively search a few or a whole lot of files at the same time. The following command recursively searches files in the /etc/httpd/conf and /etc/httpd/conf.d directories for the string VirtualHost:

$ grep -R VirtualHost /etc/httpd/conf*

Note that your system may not have any files with names starting with conf in the
/etc/httpd directory, depending on what you have installed on your system. You
can apply this technique to other files as well. Add line numbers (-n) to your grep command to find the exact lines where the search terms occur:

$ grep -Rn VirtualHost /etc/httpd/conf*

To colorize the searched term in the search results, add the --color option:

$ grep --color -Rn VirtualHost /etc/httpd/conf*

By default, in a multifile search, the file name is displayed for each search result. Use the -h option to disable the display of file names. This example searches for the string sshd in the file auth.log:

$ grep -h sshd /var/log/auth.log

If you want to ignore case when you search messages, use the -i option:

$ grep -i selinux /var/log/messages Search file for selinux (any case)
To display only the name of the file that includes the search term, add the -l option:

$ grep -Rl VirtualHost /etc/httpd/conf*

To display all lines that do not match the string, add the -v option:

$ grep -v “ 200 “ /var/log/httpd/access_log* Show lines without “ 200 “

NOTE When piping the output of ps into grep, here’s a trick to prevent the grep process from appearing in the grep results:

# ps auwx | grep “[i]nit”