Have you ever thought that the search features offered by text editors are rather simple? It’s not just you. It can be quite difficult to search through files, especially if you want to search for text that matches a pattern.
That’s where the grep command comes in handy. The grep command allows you to perform advanced searches on a text file.
In this guide, we’re going to talk about what the grep command on Linux is and how it works. We’ll walk through a few examples to help you get started using the Linux grep command. Let’s begin!
What is the Grep Command?
Grep stands for Global Search for Regular Expression and Print Out. It allows you to search a particular file using patterns called regular expressions.
Grep can be used on any file to check for pattern matches using global regular expression. It is often used to search for a string in a log file from a Linux and Unix command line.
The most simple usage of the grep command is looking for a line of text in a file. In this tutorial, we’re going to be working with a file called muffin_recipe.txt. This file contains a list of ingredients needed to make a muffin:
2 medium eggs
125ml vegetable oil
250ml semi-skimmed milk
250g golden caster sugar
400g self raising flour
Let’s say that we want to search for whether this file contains eggs
. We could do this using the grep command:
grep “eggs” muffin_recipe.txt
You need to surround your search query in either single or double quotes if it is more than one word. We have opted to do it anyway in this example because it is good practice. Our command returns:
2 medium eggs
By default, the grep command returns a list of all the lines in a file which match a particular query. Grep will match our query with the input file and return all the text on a line that meets that query. Above, you can see that “2 medium eggs” was returned, rather than just “eggs”, which was our original search query.
Using Grep to Filter a Command Output
The grep command is commonly used to filter the output of a command. This is because you can use redirection with grep; you don’t need to specify a file through which grep should search.
Consider the following example:
ls | grep “Do”
This command will return a list of all the files and folders that start with “Do” in our current working directory. We use “ls” to list all the files in our folder and then we use grep to filter out the files and folders that begin with “Do”:
Desktop
Documents
Downloads
How to Perform a Recursive Search
What makes grep really powerful is that it doesn’t have to be run on one file. Grep can search multiple files for a particular query. Consider the following command:
grep -r “egg” recipes/
This command will search for the term “egg” in a folder called recipes. This command returns a list of all the files that include “egg” as well as all the text that appears on the line that matches this term:
/Users/James/recipes/scone_recipe.txt: 1 medium egg
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
/Users/James/recipes/muffin_recipe.txt: 2 medium eggs
How to List Line Numbers
You may want to find out what line of text a particular phrase appears on. You can do this using the -n option, which displays line numbers alongside the result of a grep:
grep -n “ml” muffin_recipe.txt
This command returns:
2:125ml vegetable oil
3:250ml semi-skimmed milk
Our file contains two lines with the text ml
. These phrases appear on lines 2 and 3.
How to Exclude a Term
The grep command allows you to display text that does not match a pattern. Let’s retrieve a list of all the ingredients which are not liquid. To do this, we will assume that liquid ingredients are measured in mls:
grep -v “ml” muffin_recipe.txt
This command returns:
2 medium eggs
250g golden caster sugar
400g self raising flour
We now have a list of all the ingredients which do not contain “ml”.
How to Ignore Cases
The grep command is case sensitive by default. This means that if you search for a term, it will only return terms which match that case. You can use the -i option to ignore cases.
Let’s search for the term “EGG” in our file muffin_recipe.txt
:
grep -i “EGG” muffin_recipe.txt
This command returns: 2 medium eggs. If we did not specify the -i flag, this command would return nothing. This is because only “egg” appears in the file, and “EGG” is treated differently to “egg”.
How to Show Only Filenames
The grep command, by default, shows all the lines of text in a file which matches a particular pattern. You can override this and instruct grep to only show the names of the files containing a pattern using the -l flag. Consider this command:
grep -l “egg” recipes/*.txt
This will search for the term “egg” in all files that end in .txt in the recipes/ folder:
muffin_recipe.txt
scone_recipe.txt
This tells us that eggs are used in two recipes.
How to Search for a Whole Word
The grep command displays all the lines of text in a file where the string is contained within a larger string. For instance, if we tried to search for “5ml”, it would return all ingredients with a liquid quantity ending with “5ml”, such as “55ml”, “95ml”, and “5ml”.
You can use the -w flag to search for a whole word:
grep -w “5ml” recipes/*.txt
This command searches for the term “5ml” inside our recipes folder.
recipes/scone_recipe.txt:5ml vanilla extract
We are only shown the lines that explicitly include the word “5ml”.
How to Count Matches
Let’s find out how many wet ingredients we use in our muffin recipe. We’ll assume that dry ingredients are measured in milliliters (ml). To count the number of lines that match a particular query, you can use the -c option:
grep -c “ml” scone_recipe.txt
Our code returns: 2. Our file contains 2 instances of the “ml” pattern.
How to Print Lines After a Search
You can print out the lines of text in a file that appear before or after the result of a search.
The -A flag allows you to print the lines after a match, including the match; the -B flag prints the lines of text before a match, including the match. Let’s print out the line “2 medium eggs” and the two lines in our muffin_recipe.txt
file:
grep -A 2 “2 medium eggs” muffin_recipe.txt
Our command returns:
2 medium eggs
125ml vegetable oil
250ml semi-skimmed milk
We can print out the 2 lines which come before “400g self raising flour” using this command:
grep -B 2 “400g self raising flour” muffin_recipe.txt
This command returns the matched line and the two lines which appear before it:
250ml semi-skimmed milk
250g golden caster sugar
400g self-raising flour
How to Use Regular Expressions
It’s not surprising that grep supports regular expressions: the clue is in the name. By default, grep reads any term you specify as a basic regular expression. This means that we can conduct advanced pattern-based searches using basic regular expressions.
Let’s walk through two regular expression patterns:
- ^: Search at the beginning of a line.
- $: Search at the end of a line.
We’ll start by searching for any ingredients that begin with “250” in muffin_recipe.txt
:
grep “^250” muffin_recipe.txt
Two matches are found:
250ml semi-skimmed milk
250g golden caster sugar
You can see that our search has found any ingredients starting with “250″, irrespective of the units in which those ingredients are measured. Now, let’s generate a list of all the ingredients that end in “sugar” in muffin_recipe.txt:
grep “sugar$” muffin_recipe.txt
This searches for any lines which end in “sugar”. Our command returns: 250g golden caster sugar. Only one line of text ends in “sugar”, and that is the one that is printed to the console.
Conclusion
The grep command allows you to search through files using the Linux operating system. It can be used to search through an individual file or through multiple files.
Now you’re ready to start using the grep command like a Linux expert!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
Can I search for a whole file with this grep function ?