The grep (global regular expression print) command can be used to only display lines from a file that contain a certain string. For example, let's say that example.txt contains the following text.
Hello world How are you today? I sure could use some $ money
Grep can be used to search example.txt with a cetain string of data. In this example, only the lines that contain the string Hello are displayed.
~]# grep Hello example.txt Hello world
It is common to use pipe and grep together.
~]# cat example.txt| grep Hello Hello world
By default, grep is case sensitive. In this example, no results are displayed because the word Hello in example.txt has a capital H.
~]# grep hello example.txt
The -i or --ignore-case option can be used to ignore the case.
~]# grep -i hello example.txt Hello world
If the string of data contains one or more white spaces, place double quotes around the string. Typically, its a good idea to get in the habit of always double quote the data you are searching for.
~]# grep "are you" example.txt How are you today?
Does not contain
The -v or --invert-match option can be used to search a file for lines that do not contain a certain string. In this example, lines that do not contain the word Hello are displayed.
~]# grep -v Hello example.txt How are you today? I sure could use some $ money
Search for multiple strings of data (or)
The -E or --extended-regexp option can be used to search for numerous strings of data. In this example, the file is searched for both the words Hello and money. This executes an "or" search, not an "and" search. In this example, any line in example.txt that contains Hello or money will be displayed.
~]# grep -E "Hello|money" example.txt Hello world I sure could use some $ money
Or, the egrep command could be used.
~]# egrep "Hello|money" example.txt Hello world I sure could use some $ money
Contains entire word
The -w or --word-regexp option can be used to only display lines that contain an entire word. In this example, Hello world is not displayed because the -w option was used, and only the first three characters of the word Hello are used in the search.
~]# grep -w Hel example.txt
Using the entire word Hello in the search will return the line that contains the phrase Hello world.
~]# grep -w Hello example.txt
The -c or --count option can be used to count the number of lines that match a certain string. In this example, there is 1 line that contain the word Hello.
~]# grep -c Hello example.txt 1
Search every file for a string
The grep command with the -R or --dereference-recursive flag and -e or --regexp option can be used to search every file below a certain directory for a string of data. In this example, every file below the /opt directory will be searched for the text 'foo'.
grep -R --regexp 'foo' /opt
Often, the -i or --ignore-case flag is used to make the search case insensitive.
grep -R --ignore-case --regexp 'foo' /opt