Linux grep command

Linux grep command

 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.

Syntax:

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 patterns 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 the 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 files where no match was found.

grep -rL "SearchPattern" /home/rahul

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

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

grep -A2 "SearchPattern" myfile.csv

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

grep -B2 "SearchPattern" myfile.csv

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

grep -B2 "SearchPattern" myfile.csv

Reactions

Post a Comment

0 Comments

close