grep command is a matching string and pattern adjustment that displays matching lines from multiple files. It also works with piped output from other commands. We show you how.
The story behind grep
grep is famous in Linux and Unix circles for three reasons. First, it is enormously useful. Secondly, the wealth of options can be overwhelming. Third, it was written overnight to meet a specific need. The first two are stunner; the third is slightly less.
Ken Thompson had extracted the regular expression search capabilities from the
ed editor (pronounced ee-dee) and created a small program ̵
McMahon tried to identify the authors of the Federalist newspapers through text analysis. He needed a tool that could search for phrases and strings in text files. Thompson spent about an hour that evening turning his tools into a general tool that could be used by others and renamed
grep . He took the name of the
ed command string
g / re / p which translates as "global regular expression search."
You can see Thompson talking to Brian Kernighan about the birth of
Simple searches with grep
If you want to search for a string in a file, enter the search term and file name on the command line:
Matching lines are displayed. In this case this is a single rule. The corresponding text is highlighted. This is because on most distributions
grep is linked to:
aka grep = & # 39; grep --colour = auto & # 39;
Let's look at results where multiple lines match. We will use the word & # 39; Average & # 39; search an app's log file. Because we cannot remember whether the word is in lowercase in the log file, we use the option
-i (ignore capital):
grep -i Average geek-1.log 
Each matching line is displayed, with the corresponding text in each.
We can display the mismatched lines using the -v (invert match) option.grep -v Mem geek-1.log
There is no marking because these are the mismatched lines.
We can ensure that
grepis completely silent. The result is passed to the shell as a return value of
grep. A result of zero means that the string was found and a result of one means that the was not found . We can check the return code with the special parameters
$?:grep -q average geek-1.logecho $?grep -q howtogeek geek-1.log  echo $?
Recursive searches with grep
Use the -r (nested folders and sub-folders) recursive) option. Note that you do not specify a file name on the command line, you must specify a path. Here we search in the current folder "." And all subfolders:grep -r -i memfree.
The output contains the folder and file name of each matching line.
We can have
grepfollow symbolic links using the option
-R(recursive dereference). We have a symbolic link in this folder, called
logs-folder. It refers to
/ home / dave / logs.ls -l logs folder
Let's repeat our last search with the
-R(recursive dereference) option:grep -R -i memfree.
The symbolic link is followed and the folder to which it refers is also searched by
Search for whole words
grepcorresponds to a rule if the search target appears somewhere in that rule, including in another string. View this example. We are going to search for the word & # 39; free & # 39 ;.grep -i free geek-1.log
The results are lines with the string & # 39; free & # 39 , but they are not separate words. They are part of the string "MemFree."
grepto match Only & # 39; words & # 39 ;, use the option
-w(become regexp).grep -w -i free geek-1.logecho $?
There are no results this time because the search term & # 39; free & # 39; does not appear in the file as a single word.
Using multiple search terms  With the option
-E(extended regexp) you can search for multiple words. (The option
-Ereplaces the obsolete
This command searches for two search terms, "average" and "memfree."grep -E -w -i "average | memfree "geek-1.log
All matching lines are displayed for each of the search terms.
You can also search for multiple terms that are not necessarily whole words, but they can also be whole words.
With the option
-e(patterns) you can use multiple search terms on the command line. We use the regular expression hook function to create a search pattern. It tells
grepthat it matches one of the characters between the brackets "." This means that
grepmatches "kB" or "KB" while searching. 
Both sets are matched and in fact some lines contain both sets.
The single line that matches is found and displayed.
The opposite of this is shown only the lines that do not match . This can be useful when viewing configuration files. Comments are great, but sometimes it's hard to find the actual settings among them all. Here is the file
/ etc / sudoers:
We can effectively filter the comment lines as follows:  sudo grep -v "#" / etc / sudoers
That is much easier to parse.
Show matching text only
There may be an opportunity if you do not want to see the whole matching line, only the matching text. The option
-o(matching only) does exactly that.grep -o MemFree geek-1.log
The display is limited to only the text that matches the search term, instead of the complete matching rule.
Counting with grep
grepis not only about text, it can also be numerical information offer. We can have
grepcounting for us in various ways. If we want to know how often a search term occurs in a file, we can use the option
-c(count).grep -c average geek-1.log
grepreports that the search term occurs 240 times in this file.
You can create
grepdisplay the line number for each matching line with the option
-n(line number).grep -n Jan geek-1.log
The line number for each matching line is displayed at the beginning of the line .
Use the option
-m(max count) to reduce the number of displayed results . We are going to limit the output to five matching lines:grep -m5 -n Jan geek-1.log
It is often useful to see a few extra lines - possibly non-matching lines - for each matching line. it can help to distinguish which of the matching lines you are interested in.
Use the -A option (after context) to display some lines after the corresponding line. In this example we ask for three lines:grep -A 3 -x "20-Jan-06 15:24:35" geek-1.log
-B(context before) option to view some lines from before the corresponding line.grep -B 3 -x "20-jan-06 15:24: 35" geek-1.log
And to draw lines from before and after recording the corresponding line, use the option
-C(context).grip -C3 -x "20-Jan-06 15:24:35" geek-1.log
Show matching files
] Use the option
-l(matched files) to see the names of the files that contain the search term. Use the following command to find out which C source code files contain references to the header file
sl.h:grep -l "sl.h" * .c
The file names are displayed, not the corresponding lines.
And of course we can search for files that do not contain the search term. The option
-L(files without agreement) does exactly that.grep -L "sl.h" * .c
Beginning and end of lines
grepforce to display only matches that are at the start or end of a line. The operator for the regular expression & # 39; ^ & # 39; corresponds to the start of a line. Practically all lines in the log file contain spaces, but we are going to search for lines with a space as their first character:grep "^" geek-1.log
The lines with a space as the first character - at the beginning of the line - are displayed.
Use the regular expression operator "$" to match the end of the line. We are going to search for rules that end with "00".grep "00 $" geek-1.log
The display shows the lines with "00" as their last characters.
Using pipes with grep
Of course you can make input to
grepthe output of
carry grepin another program and
grepnestled in the middle of a pipe chain.
Let's say we have all copies of the string & # 39; ExtractParameters & # 39; want to see in our C source code files. We know there will be quite a few, so we send the output to
less:grep "ExtractParameters" * .c | less
The output is presented in
Allows you to browse the file list and use the search function of
If we grab the output from
wcand use the option
-l(lines), we can count the number of lines in the source code files that " ExtractParameters ”. (We could achieve this with the option
-c(count), but this is a convenient way to demonstrate pipes from
grep.)grep " ExtractParameters "* .c | wc -l
With the following command we enter the output from
grepand send the output from
species. We display the files in the current folder, select the files with the string "Aug" in them and sort them by file size:ls -l | grep "Aug" | sort + 4n
Let's split that up:
- ls -l : Perform a long list of files with
- grep “Aug” : Select the lines from the list
lswith & # 39; Aug & # 39; in it. Note that this would also find files that have "Aug" in their name.
- sort + 4n : Sort the output of grep on the fourth column (file size).
We get a sorted list of all files changed in August (regardless of the year), in ascending order of file size.
RELATED: How to use pipes on Linux
grep: Less a Command, More of an Ally
grep is a great tool to have at your disposal. It dates from 1974 and is still going strong because we need what it does, and nothing does it better.
grep with some regular expressions - fu really takes it to the next level. RELATED: Use regular standard expressions to search better and save time