Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Grep cheatsheet

📅 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.

[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 --exclude options.

$ grep --exclude-dir=".git" Xanadu *
$ grep --line-number Xanadu *
$ grep --color Xanadu *

On my computer, this shows the file path in purple, the line number in green and the searched text in red.

$ 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

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧