Operate grep command for searching in a file

In the first example, I will search for the user “root the Linux passwd file. To search the /etc/passwd file for the user “root”, you need to enter the following command:

grep root  /etc/passwd

Given below is the sample Output: root:x:0:0:root:/root:/bin/bash

Using grep to search only for words

When you are searching for abc, grep will match all sorts of things, viz., kbcabc, abc123, aarfbc35 and lots more combinations without obeying word boundaries. You can compel the grep command to select only those lines that contain matches to form whole words (those that match only abc word), as shown below:

grep -w "abc" file

Using grep to search two different words

To search for two different words, you must use the egrep command as shown below:

egrep -w 'word1|word2' /path/to/file

Count lines for matched words

The grep command has the ability to report the number of times a particular pattern has been matched for each file using the -c (count) option (as shown below):

grep -c 'word' /path/to/file

In addition, users may use the ‘-n’ option preceding each output line with the number of the line in the text file from which it was obtained (as shown below):

grep -n 'root' /etc/passwd

Given below are the Sample outputs: 1:root:x:0:0:root:/root:/bin/bash

Related posts

Leave a Comment