| Home | Configs | Guides | About |
Table of Contents
Commands In-Depth: grep
Noteworthy Flags
-v :reverse match
Show only the lines in the file that do NOT match the given pattern.
The following text in a file:
username=user01 password=password123 username=user02 password=password456 username=user03 password=password789
and the following grep command:
grep -v 'user02' <file>
will yield:
username=user01 password=password123 username=user03 password=password789
-i :case insensitive
Match pattern case insensitive. The below will match the following patterns:
- ee
- eE
- Ee
- EE
grep -i 'ee' /var/log/Xorg.0.log
-o :show only match
Show only the part of the file that matches. This is really only useful when using regular expressions:
Given the following lines in a file:
My username is user01. Your username is user02. Janet's username is user03.
The grep command below will show only:
user01 user02 user03
grep -o 'user0[0-9]' /tmp/users.txt
-E :use extended regular expressions
By default, grep does not use extended regular expressions. This means certain characters (such as parenthesis) are not read as regex control characters, but rather as raw text. For example, parenthesis typically depict a regex "group", but without extended regular expressions, they are simply read as parenthesis. The -E flag will cause grep to read these characters are regex control characters unless escaped.
You can also simply escape the control characters with a backslash ("\") without using -E and grep will read these characters are control characters. This can look a bit messy if you are using a lot of control characters, however.
Example:
Given the following text in a file:
My name is John. I work in a factory (on fifth street).
and the following grep statement:
grep -E 'I work in a factory \(on (.*) street\).' <file>
This will match the second line in the file and capture "John" in the first capture group.
This same statement without -E would look as follows:
grep 'I work in a factory (on \(.*\) street).' <file>
Note: -E and -e are two different arguments. Be sure to use -E and not -e.