Cancel

GREP command in Linux

grep stands for global regular expression pattern or print. It processes text line by line, and prints matched lines. It searches text from the file according to the regular expression.

Options

Options are the real power of grep. Here I’ll cover the most common options.

  • -c Count the results that match a pattern.
  • -i Case insens­itive search while matching.
  • -n Show line numbers that match a pattern.
  • -v Return all lines that do not match the pattern.
  • -o Only return the matching part of the string.
  • -w Lookup words only or match the whole word.
  • -E Extended regex or Extended Regular Expression (ERE).

I have created dummy content for you to test all the above options.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-117-generic x86_64)
166 packages can be updated
128 updates are security updates
GREP stands for global regular expression pattern or print
that processes text line by line and prints matched lines
It searches text from the file according to the regular expression
GREP command is a powerful searcher in Linux
ring
springboard
ringtone
quiet
cat
dog
id
identity

Get options listed above and put them one by one to the following structure.

You have 3 options to run the cut command. In this article, I will be using option 1 most of the time but you are free to choose other options as well.

1
2
3
4
5
6
7
8
# option 1
grep [options] 'pattern' filename.txt

# option 2
echo "166 packages can be updated" | grep [options] 'pattern'

# option 3
cat filename.txt | grep [options] 'pattern'

Let’s have a look at a bit tricky part of the grep command, which you need to know as a sysadmin, DevOps.

To match multiple words, use \| (backslash pipe).

1
2
grep "are\|is\|or" filename.txt # find these words within the word
grep -w "are\|is\|or" filename.txt # find words only

There are a lot of regex patterns we have but I cannot cover everything here. That’s why, I am gonna show you only the common usage of regex with grep command, but you can experiment with more patterns by visiting regex101 website.

To find words without \ (backslash), use -E option.

1
grep -w -E "are|is|or" filename.txt

Match either updates or updated (pick one or both and return the results).

1
grep -E "update(s|d)" filename.txt

^ (carrot) matches the word which starts of string.

1
grep -E "^GREP" filename.txt

$ (dollar) matches the word which ends of the string.

1
2
grep -E "ion$" filename.txt
grep -E "on$|nt$" filename.txt

To find empty lines only.

1
grep -n -E "^$" filename.txt