One of the really confusing things for users who are new to messing with the command line, can be trying to search with specifics. A useful little tool for aiding in this process, is called grep, or “global regular expression print,” which will search for regular statements in anything you pipe it through, and show you matches for what you looked for (if any exist.)
A rather straightforward example of this, before we continue, would be to use grep to search through the list of processes given with the command ps aux, to search for a specific application.
ps aux | grep spotify
Running this command while I had Spotify running, showed me that indeed Spotify was running, as shown in the image below. You can see Spotify has multiple processes running:
This is just one way that grep can be extremely useful. But, delving a little deeper, there are more options we can add to grep, to enhance our functionality much deeper.
Let’s say that we want to search a document, to see if that document has a specific phrase within it, (perhaps you want to see if phonenumbers.txt has your Aunt Mabel’s phone number in it.)
grep --color "Mabel" phonenumbers.txt
Note: Some distro’s have color enabled by default, and do not require its usage.
This command would show the correct line such as, “Aunt Mabel – 522-111-4321” with the text highlighted. However, there is a catch to this string, and that’s that if I had typed “mabel” with a lowercase M, it would have found nothing, assuming that inside phonenumbers.txt it’s spelled “Aunt Mabel.”
To get around potential issues like this, we can also use the option -i which means ‘case insensitive.’
grep --color -i "mabel" phonenumbers.txt
Again, assuming the word Mabel exists in the document, this would find and highlight it on that line, regardless of whether the document had the word capitalized or not.
Here are some other use cases for grep:
More options can be found on the grep man page, by typing the following into a terminal window, to read the manual for grep: man grep
You can also check out the grep documentation on the GNU website.
This is only the tip of the iceberg for what grep can do, but a good starting point for new users to help aide them in their quest to grow an epic beard, build their own kernel from scratch, and become a mighty guru in the ways of the terminal.Advertisement
Ghacks is a technology news blog that was founded in 2005 by Martin Brinkmann. It has since then become one of the most popular tech news sites on the Internet with five authors and regular contributions from freelance writers.