grep: how to search/filter a file or command output
Filter any command output easily using pipes and the ‘grep’ command.
Table of Contents
Basic usage
- Search a word in a file. This command will output every line that contains
some_word
infile.txt
.grep some_word file.txt
- Search a word in a command output. You can pipe the output of a command to
grep
to look for a word.$ lsblk | grep sda sda 8:0 0 465.8G 0 disk ├─sda1 8:1 0 499M 0 part ├─sda2 8:2 0 100M 0 part /boot ├─sda3 8:3 0 16M 0 part ├─sda4 8:4 0 143.4G 0 part ├─sda5 8:5 0 127.3G 0 part / └─sda6 8:6 0 194.5G 0 part
-
When using
grep
to filterps
command, you can enclose the first letter of the search term in brackets ([]
) to not showgrep
command itself:$ ps aux | grep mousepad ricardo 33107 0.0 0.9 699756 58988 ? Sl abr25 0:00 /usr/bin/mousepad /home/ricardo/Documents/some_file.txt ricardo 43299 0.0 0.0 9208 2604 pts/1 S+ 17:37 0:00 grep mousepad
$ ps aux | grep [m]ousepad ricardo 33107 0.0 0.9 699756 58988 ? Sl abr25 0:00 /usr/bin/mousepad /home/ricardo/Documents/some_file.txt
Patterns
- You can use regular expressions. You need to put single quotes around them (it can work without them in some cases, but it’s recommended to use them).
$ lsblk | grep 'sda[1|2]' ├─sda1 8:1 0 499M 0 part ├─sda2 8:2 0 100M 0 part /boot
$ lsblk | grep '/$' ├─sda5 8:5 0 127.3G 0 part /
- Searching filenames that contains one word OR another:
$ ls Documents/ | grep 'backup\|manual' backup-obs manual-civic.pdf manual-image-420.jpg manual-image-462.jpg manual-image-463.jpg
# Same as: ls Documents/ | grep -e 'backup' -e 'manual'
- Searching filenames that contains one word AND another:
$ ls Pictures/ | grep 'png' | grep 'IMG' IMG_6840.png IMG_7471.png
ls Pictures/ | grep -E 'IMG.*png|png.*IMG'
Command options
-v
: look for the inverse.-i
: ignore case.-c
: print the count of matching lines.$ lsblk | grep -c sda 7
-o
: print only the match part of a matching line.-R
: search recursively.-r
does not follow symlinks.grep -R someword posts/*
-A <number>
: print<number>
lines after matching lines.-B <number>
: print<number>
lines before matching lines.-C <number>
: print<number>
lines before and after matching lines.
Test with this online terminal:
If you have any suggestion, feel free to contact me via social media or email.
Latest tutorials and articles:
Featured content: