Skip to content

Instantly share code, notes, and snippets.

@vanduc95
Forked from isyufu/grep.sh
Last active November 5, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanduc95/1c1051b9c490fc104379d67d6590387e to your computer and use it in GitHub Desktop.
Save vanduc95/1c1051b9c490fc104379d67d6590387e to your computer and use it in GitHub Desktop.
grep cheat sheet
#!/bin/sh
#http://www.thegeekstuff.com/2011/01/advanced-regular-expressions-in-grep-command-with-10-examples-%E2%80%93-part-ii/
# GENERAL
# print lines begining with range of letters
grep ^[A-D] table.txt
# REGEX
# search for word which has any single character followed by ello
grep ".ello" demo.txt
# OR, all the below examples produce the same results
grep "stuff\|more" demo.txt
grep -E "stuff|more" demo.txt
grep -e "stuff" -e "more" demo.txt
# AND, there is no AND so regex works
grep 'Manager.*Sales' employee.txt
# AND & OR
grep 'Manager.*Sales\|Developer*Tech' employee.txt
# begin with 1 and endswith C
grep '^1.*C$' file.txt
# FLAGS
# print everything that doesn't contain the query
grep -v ^Da* table.txt
# -i forgets about case sensitivity
grep -i ^DA table.txt
# show only the matched string, not the entire line in which it is present within.
grep -o "Meow" table.txt
# print the file containing the query including thos within subdirs
grep -r ^David ~/scripts-x14.04/bash/*
# print the name of the file(s) which matches the query
grep -l ^David ~/some_dir/*
# count the number of matches
grep -c "stuff" table.txt
# show the line numbers of the matches
grep -n "go" demo.txt
# search only for the full word
grep -w "of" table.txt
# print 3 lines after the match (-B for before the match & -C for before and after)
grep -A 3 "of" table.txt
# this will only search through those files which have .c or .h extensions:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
# this will exclude searching all the files ending with .o extension:
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
# for directories it's possible to exclude one or more directories using the --exclude-dir parameter
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment