Here is the video version, if you prefer it:
The grep
command is used to find text patterns within files. (Ward, 2014) Its usage is as follows:
grep pattern filename
grep
outputs the lines which match the pattern
. What is the pattern
? The pattern
is anything you want to match. You can use regular expressions here, but we are going to talk about that later. pattern
, for our purposes right now, is a word or multiple words you want to find in a file. Say I had this file:
mislav@mislavovo-racunalo:~$ cat file.txt
Some line
Some other line
Here is what happens when I want to print out every line which contains the word (pattern) line
:
mislav@mislavovo-racunalo:~$ grep line file.txt
Some line
Some other line
Here is the result if I want to print every line which contains the pattern other
:
mislav@mislavovo-racunalo:~$ grep other file.txt
Some other line
If I wanted my pattern to be composed of multiple words, I would have to put them under single quotations, like this:
mislav@mislavovo-racunalo:~$ grep ‘other line’ file.txt
Some other line
If I wouldn’t I’d get an error. But you do know how to use Google for errors, do you?
Useful options are -i
for case insensitive matches (no difference between capital letters and “small” letters) and -v
for inverting matches (printing every line that does not contain a match).
Hope you found this helpful!
References
Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 18-19
Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.