Linux command: grep

Quick startgrepCommand to match patterns in text

ThisgrepCommand is a very useful tool, when you master it, it will provide you great help in your daily work.

If you want to know,greprepresentativeGlobal regular expression printing

you can use itgrepSearch for a file, or combine it with a pipe to filter the output of another command.

For example, this is how we finddocument.getElementByIdIn lineindex.mdfile:

grep -n document.getElementById index.md

use-nOption, it will display the line number:

grep -n document.getElementById index.md

A very useful thing is to tell grep to print 2 lines before the matched line and 2 lines after the matched line to provide more contextual information. use-COption, it accepts many lines:

grep -nC 2 document.getElementById index.md

By default, the search is case sensitive. use-iMark to make it insensitive.

As mentioned earlier, you can use grep to filter the output of another command. We can use the following methods to replicate the same functions as above:

less index.md | grep -n document.getElementById

The search string can be a regular expression, which makesgrepvery powerful.

Another thing you might find very useful is to use to reverse the results, excluding lines that match a specific string.-vOptions:

ThisgrepThis command can be used in Linux, macOS, WSL and wherever you have a UNIX environment

Download mine for freeLinux Command Manual


More cli tutorials: