Greenwebpage Community Blog Tutorials How to Use Grep Command in Linux
Tutorials

How to Use Grep Command in Linux

In Linux, the grep stands for global regular expression print. It is a simple command that can be utilized to search within text files. With different options, you can customize your searches for specific patterns. Additionally, you can search for or filter patterns within multiple files.

This educational post is about how to use grep commands in Linux.

How to Use Grep Command in Linux?

Using the following example, you will see the primary uses of the Grep command in Linux.

Example 1: Case Insensitive Search

The command is used to search for the pattern “gnu” in the file Linux.txt while ignoring the case of the letters, such as “GNU,” “Gnu,” or “gnu”:

grep -i "gnu" Linux.txt
 

You can notice in the above text that the word “gnu” is highlighted regardless of the case sensitivity.

Example 2: Not Matching a Pattern

The -v option is used to invert matches in grep. The provided command will filter for the whole lines in the file Linux.txt that do not contain the word “gnu”:

grep -v "gnu" Linux.txt
 

The command printed text lines that did not contain the keyword “gnu.”

Example 3: Display Line Numbers

The command with the -n option will search for the pattern “shell” in the file “Linux.txt” and display each matching line along with its line number:

grep -n "shell" Linux.txt
 

In the above output command displayed the line number contains the keyword “shell” in your file (i.e. Linux.txt). Thus, you can easily access the pattern by its line number.

Example 4: Count Matches

You can use the -c option to search only the total counts for the keyword “shell” in the Linux.txt file:

grep -c "shell" Linux.txt

Here, you can see there are 40 counts of the keyword “shell” in your Linux.txt file.

Example 5: Extended Regular Expressions

The -E option with grep enables extended regular expressions, allowing you to use the | operator to specify multiple patterns. For example, it searches for lines containing either “Linux” or “shell” in the Linux.txt file:

grep -E "shell|Linux" Linux.txt
 

This command is primarily used to search multiple patterns in your file.

Example 6: Search for Whole Words

If you want to avoid partial matches and search for the whole word “apt”, you can run this command from the terminal:

grep -w "apt" Linux.txt

You can see only the exact matches of the word “apt” returned on your terminal window.

Conclusion

With the help of the grep command, you can easily filter and search for one or more patterns within multiple files. You can use different options, including -i for case insensitivity, -n for displaying line numbers, and -c for counting specific patterns, to customize your searches.

Exit mobile version