Finding a text string in one or multiple text files is easy using the grep ( global regular expression print ) command. It does the job in a number of ways. You can search for text strings in one or many files. You can also specify additional criteria for the string, such as whether it occurs at the start or at the end of a line. If you are using multiple files for a search, grep also displays the name of the file in which the string is found. It can also display the location in the file where the string is found.
Here we show how you can find whether a particular user exists by applying the grep command on the /etc/passwd file.
$ grep Mark /etc/passwd mstyle:elBY:2216:125:Mark Style,,,:/home/mstyle:/usr/bin/sh mgany:iF5UeWQ:2259:125:Mark Gany,,,:/home/mgany:/usr/bin/sh mbuna:tQfwUNo:2318:125:Mark Buna,,,:/home/mbuna:/usr/bin/sh mblack:ipCg:2388:125:Mark Black,,,:/home/mblack:/usr/bin/sh $
This command shows that there are four users on the system with the name Mark. If you want to make a search case insensitive, you may use grep -i instead of grep . If you are interested to know how many times the string occurs in the file, without displaying the lines containing the string, use grep -c . You can even reverse the selection of lines by grep -v . In this case, all lines that don't match the string pattern are displayed.
If you want to search using a string of multiple words, enclose the words with double quotes. For example, if you want to search for "Mark Black" in /etc/passwd , you will use the grep command.
$ grep "Mark Black" /etc/passwd mblack:ipCg:2388:125:Mark Black,,,:/home/mblack:/usr/bin/sh $
For a case-insensitive search of "Mark Black," use the following command.
$ grep -i "mark black" /etc/passwd mblack:ipCg:2388:125:Mark Black,,,:/home/mblack:/usr/bin/sh $
As I mentioned earlier, the grep command can be used to search multiple files for a matching string. You need to specify all file names in which you want to search for the text string. For example, if you search for the word root in the /etc/passwd and /etc/ group files, the following result is displayed.
$ grep root /etc/passwd /etc/group /etc/passwd:root:8JgNSmFv806dA:0:3:,,,:/home/root:/sbin/sh /etc/group:root::0:root /etc/group:other::1:root,hpdb /etc/group:bin::2:root,bin $
The command shows that the word root occurs once in the /etc/passwd file and three times in the /etc/group file.
Top |