Skip to main content

Back to Basics Part 4 – using grep in GNU/Linux

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.

Grep in GNU/Linuxgrep spotify

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.

Colour highlighting results

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.”

Case insensitivity

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:

  • grep "search text" filename -- to search a file for the specified string.
  • grep "search text" file_pattern -- to search multiple files for the specified string
  • grep "Regex" filename -- to use regular expressions to search file contents.
  • grep -r "search text" * -- search in all files recursively for the text.

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.

Final words

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.