📅 2017-Sep-13 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cheatsheet, grep ⬩ 📚 Archive
Grep is the quintessential text search tool of the Unix shell. Many text search tools like ack and ag are popular now for searching in source code. But, for most common scenarios grep can still be a fast and good enough solution. It is available on every Linux machine you will be working at, so it is a huge bonus to be aware of its usage and capabilities.
:help grepin the Vim editor, you will see the origin of the name grep:
[Unix trivia: The name for the Unix "grep" command comes from ":g/re/p", where "re" stands for Regular Expression.]
$ ls -1 | grep Xanadu
Note that the search text can be a regular expression. You can find more info about regular expressions from other detailed sources.
$ ls -1 | grep "rat\|cat\|bat"
$ grep Xanadu *.txt
Note that the
*.txt is expanded by the shell and those filenames are passed to grep. Grep does not lookup the filenames.
$ grep $'\t' *.txt
More information about the search for special characters can be found in the ANSI-C Quoting section of the Bash manual.
I find the above tab search useful to check if there are any stray tab characters in the code base which is supposed to be using only spaces for indentation.
$ grep -i Xanadu *.txt
$ grep -l Xanadu *.txt
$ grep -R Xanadu *
Note again, that the wildcard is expanded by the shell and passed to grep. Grep then takes each of those directories and it recurses through them on its own.
$ grep -v Xanadu *
$ grep --exclude="*~" Xanadu *
To exclude multiple types of files, specify multiple
$ grep --exclude-dir=".git" Xanadu *
To exclude files based on glob patterns, you can also put those patterns in a file and pass it to the
--exclude-from option. However, this did not seem to work for me.
By default, grep prints the file paths which have the search text. To print the line number, along with the file paths, use the
$ grep --line-number Xanadu *
--colorcan be an useful option:
$ grep --color Xanadu *
On my computer, this shows the file path in purple, the line number in green and the searched text in red.
-Coption you can ask grep to show you some lines of context around the result lines. For example, to get 3 lines of context above and 3 lines of context below every result line:
$ grep -C 3 Xanadu *.cpp
$ grep --no-messages Xanadu *
$ grep --binary-file=without-match Xanadu *
$ grep --max-count=2 Xanadu *
Tried with: Grep 3.1 and Ubuntu 18.04