Linux commands: grep
By Flavio
Published · Updated
Tagged: CLI
Learn how the Linux grep command matches patterns in files or piped output, with -n for line numbers, -C for context, -i to ignore case, and -v to invert.
The grep command is a very useful tool, that when you master will help you tremendously in your day to day.
If you’re wondering,
grepstands for global regular expression print
You can use grep to search in files, or combine it with pipes to filter the output of another command.
For example here’s how we can find the occurrences of the document.getElementById line in the index.md file:
grep document.getElementById index.md

Using the -n option it will show the line numbers:
grep -n document.getElementById index.md

One very useful thing is to tell grep to print 2 lines before, and 2 lines after the matched line, to give us more context. That’s done using the -C option, which accepts a number of lines:
grep -nC 2 document.getElementById index.md

Search is case sensitive by default. Use the -i flag to make it insensitive.
As mentioned, you can use grep to filter the output of another command. We can replicate the same functionality as above using cat:
cat index.md | grep -n document.getElementById

The pattern is a regular expression, so . matches any character. Use -F to search for a fixed string. Use -r to search a whole folder recursively:
grep -rn getElementById src/
Another thing you might find very useful is to invert the result, excluding the lines that match a particular string, using the -v option:

The
grepcommand works on Linux, macOS, WSL, and anywhere you have a UNIX environment
Want me to talk about your product? You can sponsor this site.
Related posts about cli: