To build upon @imhigh.today’s answer imagine you asked a friend to read a newspaper line by line and find any line that had the word dog in it and to cut it out and give it to you.
That’s what grep
does on a very basic level.
So here’s a real world example to help you understand. I wanted to get a list of every kernel I have used on my Arch Desktop. Arch stores all of the package managers pacman
's action in a log file /var/log/pacman.log
.
Now, I could open it up in a GUI text editor, run the find function, find every instance of the upgrade, and copy it into a different file. Problem with this is that my pacman.log file is long. Like, 24529 lines long. That would take forever!
Instead let’s use our grep
command. Previous knowledge tells me that when I upgrade to a new kernel on Arch, it is called “linux” so let’s start with that.
grep linux /var/log/pacman.conf
Look at the results here.
That’s still really long and includes all sorts of stuff that I don’t want. Let’s refine it a bit more.
Thankfully, we don’t have to look very far. The 3rd line looks like this:
[2017-10-16 07:39] [ALPM] upgraded linux (4.13.5-1 -> 4.13.6-1)
Okay the keywords “upgraded linux” seems like what I want. Because it’s multiple words separated by a space, I need to use quotes or it won’t work the way we expect it too.
grep "upgraded linux" /var/log/pacman.log
Results here.
Well that’s closer, but that is also including the firmware and api headers. There might be a better way to filter this, but if you notice, the lines I want look just like this upgraded linux (...
so there is a space after linux while the other lines have a hypen after linux. So let’s just grep
that.
grep "upgraded linux " /var/log/pacman.log
Ah! Finally the information we wanted!
Results here.