📅 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 grep
in 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.
tab
for example:$ 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.
-i
option:$ grep -i Xanadu *.txt
-l
option:$ 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 *
--exclude
option:$ grep --exclude="*~" Xanadu *
To exclude multiple types of files, specify multiple --exclude
options.
--exclude-dir
option:$ 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 --line-number
option:
$ grep --line-number Xanadu *
--color
can 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.
-C
option 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
--no-messages
option:$ grep --no-messages Xanadu *
-I
or --binary-file=without-match
option:$ grep --binary-file=without-match Xanadu *
$ grep --max-count=2 Xanadu *
Tried with: Grep 3.1 and Ubuntu 18.04