Advanced grep

We have already discussed a few popular options for grep to alter its default behavior: --ignore-case (-i), --invert-match (-v), and --word-regexp (-w). As a reminder here's what they do:

  • -i allows us to search case-insensitively
  • -v only prints lines that are not matched, instead of matched lines
  • -w only matches on full words that are surrounded by spaces and/or line anchors and/or punctuation marks

There are three other options we'd like to share with you. The first new option, --only-matching (-o) prints only the matching words. If your search pattern does not contain any regular expressions, this will probably be a pretty boring option, as you can see in this example:

reader@ubuntu:~/scripts/chapter_10$ grep -o 'cool' ...

Get Learn Linux Shell Scripting - Fundamentals of Bash 4.4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.