How To Use grep Command In Linux / UNIX With Practical Examples

How To Use grep Command In Linux / UNIX With Practical Examples

The grep command is a utility that searches for specified patterns within input files and outputs the lines that contain them. It is a powerful tool that can be used to search for text patterns in one or more files, or even search recursively through a directory tree.

Here are some examples of how to use the grep command:

  1. Search for a pattern in a single file:
grep pattern file.txt
Sourc‮l.www:e‬autturi.com

This searches for the pattern in file.txt and prints the lines that contain it.

  1. Search for a pattern in multiple files:
grep pattern file1.txt file2.txt file3.txt

This searches for the pattern in file1.txt, file2.txt, and file3.txt and prints the lines that contain it.

  1. Search for a pattern recursively through a directory tree:
grep -r pattern directory/

This searches for the pattern in all files under the directory/ directory and its subdirectories, and prints the lines that contain it.

  1. Ignore case when searching:
grep -i pattern file.txt

This searches for the pattern in file.txt and prints the lines that contain it, ignoring the case of the characters.

  1. Invert the match:
grep -v pattern file.txt

This searches for lines in file.txt that do NOT contain the pattern and prints those lines.

  1. Count the number of lines that contain the pattern:
grep -c pattern file.txt

This searches for the pattern in file.txt and prints the count of the number of lines that contain it.

  1. Use a regular expression as the pattern:
grep '^[0-9]*$' file.txt

This searches for lines in file.txt that contain only digits (0-9) and prints those lines. The ^ and $ characters are used to match the start and end of the line, respectively, and the [0-9]* pattern matches any number of digits.

These are just a few examples of how the grep command can be used. For more options and usage examples, you can refer to the grep man page by typing man grep at the command prompt.

Created Time:2017-10-29 22:08:34  Author:lautturi