What are useful arguments that we can pass to `grep`?

Question

In the second lesson on the grep command we find explanations of the arguments -R, for recursive searches, and -l, for outputting matching files only. What are other useful arguments for us to pass to grep?

Answer

A complete list of arguments to grep can be found in the so called man (short for manual) page for the function. This entry can be found by searching something along the lines of “grep man page”. For now I will provide three commands that come in handy often.

  1. -e. Since grep stands for global regular expressions, there should be some way to search with regular expressions instead of simply searching for exact string matches as we have been doing. -e enables us to do just that.
  2. -v. This useful argument allows you to search for non-matches. So it is the inverse of the usual behavior of grep.
  3. -i. This argument allows you to search for a match in a case-insensitive way. So for example, “hit”, “HIT”, and “HiT” all match a search for “hit”.
10 Likes

I don’t get the difference between -e and -i. Could somebody show me the examples of using -e?

1 Like

Well, this answer is wrong about what -e does, it’s a regexp pattern either way. (@zjedwin)

$ echo asdf | grep 'a.df'
asdf

-e is just to escape the pattern in case it starts with - so that the pattern isn’t interpreted as another flag. For a a lot of purposes -e therefore does nothing.

A more useful flag would be -P which interprets the pattern as a perl regexp instead (more powerful)

Or -F which matches an exact string (turns off regex)

If not restricted to grep then you might want to use something like rg or ag which are a bit more clever about doing “the right thing” and are therefore nicer for interactive use.

2 Likes