EXPLORING THE GREP COMMAND

Perhaps one of the most useful and powerful tools on any Linux system is the grep command. The grep command is a tool that searches through input and reports any matches based on a specified search criteria. The grep command is used in pipes or directly against either a single file or multiple files. It can even search recursively through all of the files in a directory or subdirectory.

Like nearly all Linux commands, grep has a large number of options; however, only a few are shown. For example, the following command searches through all files ending in .txt for the string Linux:

# grep -n Linux *.txt

It will display the number of the line in the file on which it was found, for example:

myfile:8:this has something to do with Linux

It shows that the file myfile.txt contains the string Linux on line eight. If you want to suppress the output somewhat and obtain only the filename itself, you would use:

# grep -l Linux *.txt

myfile.txt

Only the filename is returned here. To see how many lines contained the

# grep -c Linux *.txt

myfile:1

This shows that Linux was found on one line in the file. You can also use grep in pipes, like this:

# cat /var/log/messages|grep kernel

This would display any lines containing the string "kernel" from the output of the cat command. You can use regular expressions with grep as well:

# grep -E '^Jan.*su\(' /var/log/messages

Jan 1 01:51:11 logan su(pam_unix)[28813]: session opened for user root by

joe(uid=0)

Jan 2 21:26:40 logan su(pam_unix)[28813]: session closed for user root

This tells grep to find any matches in the /var/log/messages file, which start with Jan at the beginning of the line,

followed by any number ofcharacters and that also contain su ( on the same line).