Skip to content

Instantly share code, notes, and snippets.

@AbhishekPednekar84
Last active February 10, 2020 12:39
Show Gist options
  • Save AbhishekPednekar84/a4d5064ad4f2cc8163d8b7b76dd13321 to your computer and use it in GitHub Desktop.
Save AbhishekPednekar84/a4d5064ad4f2cc8163d8b7b76dd13321 to your computer and use it in GitHub Desktop.

Usage of the grep command in Linux

This list is by no means complete and only aims to display some common usages of the grep command.

Accessing the help manual

man find


Checking the version of grep

grep -V

Note By default, Linux will have the GNU grep whereas macOS will have the BSD grep.


Common constructs used with grep

Whole word search with -w

grep -w "John" file.txt will look for the word John in file.txt.

Case-insensitive search with -i

grep -wi "John doe" file.txt will perform a case insensitive search for John Doe.

Display line numbers corresponding to the search results with -n

grep -win "doe" file.txt will perform a case insensitive for doe in the file and display the results along with the corresponding line numbers from file.txt.

Recursive search in the current and sub-directories with -r

grep -winr "doe" will perform a case insensitive recursive search for doe and display the results with line numbers.

Display only the files containing the search results with -l

grep -wirl "doe" will perform a case insensitive recursive search for doe and display only the file names that contain the search text.

Display the number of matches in each file with -c

grep -wirc "doe" file.txt will display the files containing the search string along with the number of hits found in each file.

Invert match with -v

grep -winv "Jane" file.txt will display all the lines not containing Jane.

Display lines after context with -A

grep -wA 2 "jane" file.txt will display the two lines from the file that follow the lines containing jane.

Display lines before context with -B

grep -wB 2 "jane" file.txt will display the two lines from the file that precede the lines containing jane.

Display lines before and after context with -C

grep -wC 2 "jane" file.txt will display the two lines from the file that precede and follow the lines containing jane.


Using RegEx with grep

grep "...-...-.... file.txt` will display strings having the format abc-efg-hijk or 123-456-7890.

Below command will work for GNU grep only
grep -P "\d{3}-\d{3}-\d{4}" file.txt will display numbers having the format 123-456-7890.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment