2 minutes
Linux Tip of the Day - grep
What is grep?
According to the man page, grep
is used to print lines that match patterns. It can be used to match regular expressions in plaintext.
grep
can be used by running grep [OPTION...] PATTERNS [FILE...]
❯ grep export ~/.zshrc
export PATH="$HOME/.local/bin:$PATH"
grep
is helpful when parsing log files or files with a lot of text.
❯ grep GNOME /var/log/boot.log
[ OK ] Started GNOME Display Manager.
Starting GNOME Display Manager...
Because it can search using regular expressions, it is case sensitive. Using grep gnome /var/log/boot.log
in this case would show no results but we can use different options to help with this.
-i, --ignore-case
grep -i
ignores case when searching for matches.
❯ grep -i gnome /var/log/boot.log
[ OK ] Started GNOME Display Manager.
Starting GNOME Display Manager...
-v, --invert-match
grep -v
finds non-matching lines. This is helpful to exclude certain search terms
❯ tail -2 /var/log/boot.log
[ OK ] Started Manage, Install and Generate Color Profiles.
[ OK ] Started GNOME Display Manager.
❯ tail -2 /var/log/boot.log | grep -vi gnome
[ OK ] Started Manage, Install and Generate Color Profiles.
-c, --count
grep -c
can be used to provide the count for lines.
❯ grep -ci gnome /var/log/boot.log
11
Using regular expressions with grep
Let’s say we have a test file:
❯ cat testfile
test
TEST
TeST
123test
1TE34St
456tEST
Look for lines with test
regardless of case:
❯ grep -i test testfile
test
TEST
TeST
123test
456tEST
Look for lines that start with capital T
:
❯ grep '^T' testfile
TEST
TeST
Look for lines that end with lowercase t
:
❯ grep 't$' testfile
test
123test
1TE34St
You can use -E, --extended-regexp
to find more patterns using regular expressions. This is the same as egrep
.
Look for anything that starts with a number:
❯ grep -E '^[0-9]{1}' testfile
123test
1TE34St
456tEST
Look for lines that start with 3 numbers:
❯ grep -E '^[0-9]{3}' testfile
123test
456tEST
Look for anything that ends with test
❯ grep -E 'test$' testfile
test
123test
There are a ton of regex patterns that can be used. Regex101 can be used to test different regular expressions.
I’ve only provided a few options with basics for grep
but it is a powerful tool that can be used to parse plaintext files.