How to use grep to search for a string in a file on Shell

1 GREP command-overview

grep command, which means Global regular expression printingIt is still one of the most feature-rich commands in the Linux terminal environment. It happens to be a powerful program that enables users to sort input according to complex rules, making it a fairly popular link in many command chains. The grep command is mainly used to search for text or in any given file for lines that match the provided word / string. By default, grep displays matching lines, and it can be used to search for text lines that match one or more regular expressions without causing any interference, and only output matching lines.

2 basic grep command syntax

The basic grep command syntax is as follows:

grep 'word' filename
grep 'word' file1 file2 file3
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName

3 how to use grep command to search in the file

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

grep tom /etc/passwd

Given below is the sample output:

tom:x:1000:1000:tom,,,:/home/tom:/bin/bash

You can choose to instruct grep to ignore word case, that is, use the -i option to match abc, Abc, ABC and all possible combinations as follows:

grep -i "tom" /etc/passwd

4 Recursively use grep

If you have a bunch of text files in the directory hierarchy (such as Apache configuration files in / etc / apache2 /), and you want to find files that define specific text, use the -r option of the grep command to do the following: recursively search for. This will perform a recursive search operation on the string “197.167.2.9” (shown below) in the directory / etc / apache2 / and all its subdirectories:

grep -r "mydomain.com" /etc/apache2/

Alternatively, you can use the following command:

grep -R "mydomain.com" /etc/apache2/

Here is sample output from a similar search on the Nginx server:

grep -r "mydomain.com" /etc/nginx//etc/nginx/sites-available/mydomain.com.vhost:        if ($http_host != "www.mydomain.com") {

Here, you will see the result of mydomain.com on different lines, before the result is to find the file name of the file (for example /etc/nginx/sites-available/mydomain.com.vhost). By using the -h option (described below), you can easily suppress the inclusion of file names in the output data: grep -h -R “mydomain.com” / etc / nginx /. Here is sample output:

grep -r "mydomain.com" /etc/nginx/if ($http_host != "www.mydomain.com") {

5 Use grep to search only words

When you search for abc, grep will match a variety of things, namely kbcabc, abc123, aalfbc35 and more other combinations without having to obey word boundaries. You can force the grep command to select those lines that only contain matches to make up the entire word (only match abc words), as shown below:

grep -w "abc" file.txt

example:

Grep is only for whole words

6 Use grep to search for two different words

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

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

7 lines matching words

The grep command can use the -c (count) option to report the number of times each file matches a specific pattern (as shown below):

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

In addition, users can use the “-n” option before each output line and get the line number from the text file (see below):

grep -n 'root' /etc/passwd

The following is sample output:

1:root:x:0:0:root:/root:/bin/bash

8 Grep anti-match

The user can use the -v option to print reverse matches, which means it will match only those lines that do not contain the given word. For example, by using the following command, print all lines that do not contain the word par:

grep -v par /path/to/file

9How to list only the names of matching files

You must use the -l option to use the following command to list file names that mention specific words in their content, such as the word “primary”:

grep -l 'primary' *.c

Finally, you can choose to use the following command to force grep to display a specific color of output: ad

ad

grep --color root /etc/passwd

The following is sample output:

List only the names of files matching grep

10 How to make grep command handle multiple search modes

In some cases, you may want to search for multiple patterns in a given file (or set of files). In this case, you should use the ‘-e’ command line option provided by grep.

For example, suppose you want to search for the words “how”, “to”, and “forge” in all text files that exist in the current working directory, then you can do the following:

ad

grep -e how -e to -e forge *.txt

This is the command in execution:

Multiple search modes in Grep

The “-e” command line option can also help if the pattern starts with a hyphen (-). For example, if you want to search for “-how”, the following command will not help:

grep -how *.txt

When you use the -e command line option, the command will understand what you are trying to search in this case:

grep -e -how *.txt

Both commands are working:

Grep -e switch

11 How to limit grep output to a specific number of lines

If you want to limit grep output to a specific number of lines, you can use the ‘-m’ command line option to complete. For example, suppose you want to search the testfile1.txt for the word “how” containing the following line:

Limit Grep output

However, grep is required to stop searching after finding 3 lines containing the search pattern. Therefore, to do this, you can run the following command:

ad

grep "how" -m3 testfile1.txt

This is the command in execution:

Grep -m switch

Continue, this is what the man page for the command shows:

If the input is standard input from a regular file, and NUM matching lines are output, grep ensuresthat the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search.

So, for example, if you have a bash script with a loop and want to get a match in each loop iteration, then using ‘grep -m1’ is sufficient.

12 how to make grep get the pattern from the file

If necessary, you can also use the grep command to get the pattern from the file. The tool’s -f command line option allows you to do this.

For example, suppose you want to search for the words “how” and “to” in all .txt files in the current directory, but want to provide these input strings through a file named “input”, then you can do as follows This one:

grep -f input *.txt

This is the command in execution:

Grep mode for getting files

13 How to make grep display only the lines that exactly match the search pattern

So far, we have seen that by default grep will match and display the complete line containing the search pattern. However, if you want grep to display only the lines that exactly match the searched pattern, you can use the ‘-x’ command line option to complete.

For example, suppose the testfile1.txt file contains the following lines:

Only show exact matches

The pattern you are searching for is “How are you?” Therefore, to ensure that grep only displays lines that exactly match the pattern, use it as follows:

grep -x "how are you?" *.txt

This is the command in execution:

Grep -x switch takes effect

14 How to force grep to display nothing in the output

In some cases, you do not need the grep command to produce anything in the output. Instead, you just want to know if a match was found based on the exit status of the command. This can be achieved using the -q command line option.

When the -q option mutes the output, you can pass’ echo $? ‘Confirm the exit status of the tool. command. For grep, when the command succeeds (indicating that a match is found), it exits with status 0, and if no match is found, it exits with status 1.

The following screenshot shows the successful and failed scenario:

Grep does not show output

15 how to make grep display the names of files that do not contain search patterns

By default, the grep command displays the name of the file containing the search pattern (and matching lines). This is very logical because this is what the tool expects. However, in some cases, the requirement may be to obtain the names of those files that do not contain the search pattern.

This can also be done using grep-the L option allows you to do this. So, for example, to find all text files that do not contain the word “how” in the current directory, you can run the following command:

grep -L "how" *.txt

This is the command in execution:

Grep inversead

16 How to suppress the error messages generated by grep

If necessary, you can also force grep to mute all error messages displayed in the output. This can be done using the -s command line option. For example, consider the following scenario, where grep generates errors / warnings related to the directories it encounters:

Suppress errors in grep

Therefore, in this case, the -s command line option will help. as follows.

grep -s switch

Therefore, you can see that the error / warning is muted.

17 How to make grep search directories recursively

It is clear from the example in the previous point that by default, the grep command does not perform recursive search. To ensure that your grep search is recursive, use the -d command line option and pass the value ‘recurse’ to it.

grep -d recurse "how" *

Note 1: We can also use the -d option to ignore the directory-related error / warning messages discussed in the previous section-all you have to do is pass the value “skip” to it.

Note 2: Use ‘–exclude-dir =[DIR]The ‘option can exclude directories that match the pattern DIR from the recursive search.

18 How to make grep terminate file names with NULL characters

As we have already discussed, when you only want the tool to display file names in the output, grep’s -l command line option will be used. E.g:

Grep empty file termination

Now, what you should know here is that each name in the above output is separated / terminated by a newline. This is the method you can verify:

Redirect the output to a file, and then print the file contents:

Grep -l switch

Therefore, the output of the cat command confirms whether there is a line break between file names.

However, you may already know that newlines can also be part of the file name. Therefore, in the case where the file name contains a newline character and they are also separated / terminated by the newline character, it becomes difficult to process grep output (especially when accessing the output through a script).

If the delimiter / terminator is not a newline, it is even better. Well, you will be happy to know that grep provides the command line option -Z to ensure that the file name is followed by a NULL character instead of a newline character.

Therefore, in this example, the command becomes:

grep -lZ "how" *.txt

This is how we confirm whether there is a NULL character:

Check NULL character

Here are the relevant command line options you should know:

 -z, --null-dataTreat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) insteadof a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names.

19 more GREP command examples

In the second GREP command tutorial, you can find more examples of how to use this Linux command.

  • How to use Grep to perform a pattern search in a file

Source

Sidebar