Shells: What is grep

From my last post [ link ], some of you may noted the use of grep command, I used for process search. grep is a Unix command that allows you to search for a pattern in a list of files [ man Page ]. We are going to test usage with /etc/passwd file.

The passwd file is used for storing encrypted-passwords for the users. Without a passwd file no one can able to login again. So it is better to make a copy of it before we accidentally delete or edit the file, even we are not intended to do so.

#cp /etc/passwd /etc/passwd.bck

Before start, just go and check how passwd file is looks like.

#nano /etc/passwd

First we are going to check, whether there is an entry for root user.

#grep root /etc/passwd


check the existence of the user www-data with bin in the same line

#grep www-data /etc/passwd | grep bin

What if the list which not having the string www-data, we are using -v for invert search, which is used to filter the result.

#grep bin /etc/passwd | grep -v www-data

You will get a large list which obviously not having the entry www-data.

For higher level usage try the following:


example: grep "riazali$" MyDataFile > MyResultsFile

The '$' matches end-of-line.

If you are using a variable, containing the name (in your shell script) , then:



Post a Comment