You’re looking for that one file, the one that contains the all important information for your next meeting. Do you manually search all of your files? That will take time. Instead we use a little Linux command line magic.Grepis a pattern matching command that we can use to search inside files and directories for specific text.Grepis commonly used with the output of one command, piped to be the input of the grep command. For example we can search inside a file for a specific string of text using thelesscommand, and pipe the output togrep.
In this how-to we will use thegrepcommand and commonly added arguments to search for specific strings of data within files. We’ll begin by setting up a small directory of test files as searching an entire filesystem can take some time and create a lot of results.
All the commands in this how-to will work on most Linux machines. We’ve used an Ubuntu LTS install but you could run this how-to on aRaspberry Pi. All of the how-to is performed via the Terminal. You can open a terminal window on most Linux machines by pressingctrl, altandt.
Set Up a Test Environment for grep
Asgrepcan be used in lots of different ways we need to set up a directory and some content that allow us to explore its uses. In this section we will create this test environment.
1.Set up atestdirectory and change directory so that you are inside it.
2.Create 4 files, test1, test2, test3 and test4.
3.Edittest1usingnanoto contain the following names on separate lines.Note that intest1none of the names contain capitals. After editing innanopresscontrol xto exit, pressyto confirm the save and then pressenter.
Get Tom’s Hardware’s best news and in-depth reviews, straight to your inbox.
4.Add the following text to the file. Then press CTRL + X, then Y and Enter to save and exit.
5.Edittest2usingnano.Intest2we will add a single longer line of test containing the namesteve.
6.Add the following text to the file. Then press CTRL + X, then Y and Enter to save and exit.
7.Edittest3innano.Similar totest1we will add a list of names on separate lines but this list will include the namesteven.
8.Add the following text to the file. Then press CTRL + X, then Y and Enter to save and exit.
9.Finally edittest4to complete our test environment.Note that in this file we are using a capital letter at the start ofSteve.
10.Add the following text to the file. Then press CTRL + X, then Y and Enter to save and exit.
Simple Searches with grep
Searching a file for a specific string is extremely useful. For example when debugging an error in a log file. Let’s start usinggrepin its most basic form.Thegrepcommand syntax is simplygrepfollowed by any arguments, then the string we wish to search for and then finally the location in which to search.
1.Searchtest1for the stringsteveusing grep.The search criteria is case sensitive so ensure that you’re searching correctly. Notice that the wordsteveis simply returned in red to indicate it has been found in the file.
2.Search for the same string in multiple files.We can simply add a list of files to thegrepcommand for it to search. Notice that, with multiple search areas, the returned results are tagged with each filename from which the result is found. Also notice thatgrepreturns the complete line of text that contains the searched string.
3.Search all files within the directory.Adding an asterisk forcesgrepto search all files within the current directory. Notice that the returned results include the result fromtest3where the search stringsteveis contained within Steven. Note also that these results don’t contain the result fromtest4as in its basic form thegrepcommand is case sensitive.
4.Add the argument-ito makegrepcase insensitive.This will return results from all four of the test files in the directory.
Piping output to grep
The strongest use case for grep is when it is paired with another command. Using pipes we send the output of a command togrepand use it to search for patterns / keywords.
1.Open a new terminal window.
2.Uselsusbto list all of the USB devices attached to your machine.This will also list internal USB devices, such as laptop webcams. The output will differ depending on your machine, but you should be met with a wall of text.
3.Use thelsusbcommand again, but this time usegrepto search for Linux.By adding a pipe betweenlsusbandgrepthe output of the first command is used as the input of the second.
Using dmesg and grep to Inspect the Kernel Ring Buffer
Let’s try something a little more complex. This time we’ll usedmesgandgrepto inspect the Kernel Ring Buffer (essentially the kernel’s log file). We are going to search for a keyword indmesg, “secureboot”, and confirm that it is enabled.
1.Open a terminal and run the dmesg command using sudo.This will print a wall of console output to the terminal, something that we can search using grep.
2.Use thegrepcommand to search for “secureboot” in thedmesgoutput. Use the-iargumentto turn off case-sensitivity so that we catch every occurrence of secureboot. The output will show the lines at which secureboot appears indmesg.
Other Uses of grep
Like many Linux commands there are many useful additions and variants for thegrepcommand. Let’s look at a couple of interesting examples.
1.Perform an inverted search using the-vargument.This will return a list of every line from the test environment files that doesn’t contain the search stringsteve.This argument is useful to dismiss occurrences of strings in logs or files when debugging an issue. Note that again the results are case sensitive and therefore they include the line containing the capitalizedSteve ?fromtest4.
2.Combine the-vand-iarguments to exclude all matching strings regardless of case.
3.Search for a string that contains non alphanumeric text or spaces.If you include a search string with a space or other non alphanumeric text this can break thegrepcommand syntax, to create a search string containing these you need to use quotes to contain the string. In this step we are searching for “Steve ?” which is contained in thetest4file.
Searching Subdirectories with grep
Often we will want to search for a string in the files contained in sub directories. We can do this simply by adding the-rrecursive argument to thegrepcommand.
1.Create a subdirectory containing a test file within thetestdirectory.
2.Open test5 using the nano text editorandadd the text “steve in a sub directory” to the file. Then press CTRL + X, then Y and Enterto save and exit.
3.Return to thetestdirectoryandperform a search adding the-roption.Notice that the result fortest5includes the location of the file listed in the output.
With grep in Linux, you have a good collection of approaches for searching out file contents across your system. As with many Linux commands it can be worthwhile looking at the help menu to see all the varied arguments you can add togrep. Rungrep –hin a terminal emulator to check out all the options.
MORE:How To Kill a Process in Linux
MORE:How To Find Files in Linux
Jo Hinchliffe is a UK-based freelance writer for Tom’s Hardware US. His writing is focused on tutorials for the Linux command line.