1. Home
  2. Linux
  3. Linux Filters
  4. Linux – grep

Linux – grep

Linux grep command

The Linux grep command stands for “Global Regular Expression Print“. The grep command-line utility is used for searching content from files based on a pattern or regular expression.

Synatx:

grep "PATTERN" [FILE]

Example:

Search all users under /etc/passwd have the bash shell.

grep "bash" /etc/passwd

Grep command can also take the output of another command as input using pipes. For example:

cat /etc/passwd | grep "bash"

Grep uses -i option to run a case-sensitive search.

grep -i "SearchPattern" filename

Search Recursively in Directory Tree

Using the -r switch grep to search for pattern recursively for all files under the specified directory and their subdirectories.

grep -r "SearchPattern" /home/rahul

The default grep prints the matching content on the output with the respective file names. You can hide the content and display only filename in grep output.

Use -l to print pattern matching filenames.

grep -rl "SearchPattern" /home/rahul

Use -L to revert the output. This will print only those file where no match found.

grep -rL "SearchPattern" /home/rahul

This is a useful feature of grep command. You can print the defined number of lines just before line matches the pattern or just after lines of matches pattern.

Use -A followed by number of lines to print lines before the matching pattern line.

grep -A2 "SearchPattern" myfile.csv

Use -B followed by number of lines to print lines after the matching pattern line.

grep -B2 "SearchPattern" myfile.csv

Use -C followed by number of lines to print lines before and after the matching pattern line.

grep -B2 "SearchPattern" myfile.csv
Tags , ,