قالب وردپرس درنا توس
Home / Tips and Tricks / How to use the grep command on Linux

How to use the grep command on Linux



  A terminal prompt on a Linux PC.
Fatmawati Achmad Zaenuri / Shutterstock

The Linux 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

The command 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 ̵

1; for his own use – to search text files. His head of department at Bell Labs, Doug Mcilroy, approached Thompson and described the problem one of his colleague Lee McMahon was facing.

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

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:

  grep dave / etc / password in a terminal widnow 

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 [19659014]   grep -i Average geek-1.log in terminal window  

Each matching line is displayed, with the corresponding text in each.

 Output of grep -i Average geek -1.log in a terminal window

We can display the mismatched lines using the -v (invert match) option.

  grep -v Mem geek-1.log 

 grep -v Mem geek-1.log in a terminal window

There is no marking because these are the mismatched lines.

 output of grep -v Mem geek-1.log in a terminal window

We can ensure that grep is 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.log 
  echo $? 
  grep -q howtogeek geek-1.log [19659026] echo $? 

 grep -q average geek-1.log in a terminal window

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. 

 grep -r -i memfree. in a terminal window

The output contains the folder and file name of each matching line.

 output of grep -r -i memfree. in a terminal window

We can have grep follow 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 

 ls -l logs folder in a terminal window

Let's repeat our last search with the -R (recursive dereference) option:

  grep -R -i memfree. 

 grep -R -i memfree. in a terminal window

The symbolic link is followed and the folder to which it refers is also searched by grep .

 Export of grep -R -i memfree. in a terminal window

Search for whole words

By default, grep corresponds 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 

 grep -i free geek-1.log in a terminal window

The results are lines with the string & # 39; free & # 39 , but they are not separate words. They are part of the string "MemFree."

 Output of grep -i free geek-1.log in a terminal window

To force grep to match Only & # 39; words & # 39 ;, use the option -w (become regexp).

  grep -w -i free geek-1.log 
  echo $? 

 grep -w -i free geek-1.log in a terminal window

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 [19659005] With the option -E (extended regexp) you can search for multiple words. (The option -E replaces the obsolete egrep version of grep .)

This command searches for two search terms, "average" and "memfree."

  grep -E -w -i "average | memfree "geek-1.log 

 grep -E -w -i" average | memfree "geek-1.log in a terminal window

All matching lines are displayed for each of the search terms.

 Output of grep -E -w -i" average | memfree "geek-1.log in a terminal window

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 grep that it matches one of the characters between the brackets "[]." This means that grep matches "kB" or "KB" while searching. [19659006]   grep -e MemFree -e [kK] B geek-1.log in a terminal window

Both sets are matched and in fact some lines contain both sets.

   Output of grep -e MemFree -e [kK] B geek-1.log in a terminal window [19659065] Matching lines exactly </h2>
<p>  The <code> -x </code> (line regexp) only comes over with lines where the <em> entire line </em> matches the search term. Let's look for a date and time stamp that we know to appear only once in the log file: </p>
<pre>  grep -x "20-Jan - 06 15:24:35" geek-1.log </pre>
<p>  <img class= 

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 :

 Content of the file / etc / sudoers in a terminal window

We can effectively filter the comment lines as follows: [19659013] sudo grep -v "#" / etc / sudoers

 sudo grep -v

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 

 grep -o MemFree geek-1.log in a terminal window

The display is limited to only the text that matches the search term, instead of the complete matching rule.

 output of grep -o MemFree geek-1.log in a terminal window

Counting with grep

grep is not only about text, it can also be numerical information offer. We can have grep counting 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 

 grep -c average geek-1.log in a terminal window

grep reports that the search term occurs 240 times in this file.

You can create grep display the line number for each matching line with the option -n (line number).

  grep -n Jan geek-1.log 

 grep -n jan geek -1.log in a terminal window

The line number for each matching line is displayed at the beginning of the line .

 Output of grep -n jan geek-1.log in a terminal window

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 

 grep -m5 -n Jan geek-1.log in a terminal window

Add context

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 

 grep -A 3 -x

Use the -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 

 grep -B 3 -x

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 

 grip -C3 -x

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 

 grep - l " sl.h "* .c in a terminal window

The file names are displayed, not the corresponding lines.

 Output of grep -l "sl.h" * .c in a terminal window

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 

 grep -L "sl.h" * .c in a terminal window

Beginning and end of lines

We can grep force 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 

 grep "^" geek-1.log in a terminal window

The lines with a space as the first character - at the beginning of the line - are displayed.

 Grab output "^" geek-1.log in a terminal window

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 

 grep "00 $" geek-1.log in a terminal window

The display shows the lines with "00" as their last characters.

 output of grep "00 $" geek-1.log in a terminal window

Using pipes with grep

Of course you can make input to grep the output of carry grep in another program and grep nestled 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 

 "ExtractParameters" * .c | less in a terminal window

The output is presented in less .

 Output of grep "ExtractParameters" * .c | less in a terminal window

Allows you to browse the file list and use the search function of less .

If we grab the output from to to wc and 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 grep -c (count), but this is a convenient way to demonstrate pipes from grep .)

  grep " ExtractParameters "* .c | wc -l 

 "ExtractParameters" * .c | wc -l in a terminal window

With the following command we enter the output from ls to grep and send the output from grep 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 

 ls -l | grep

Let's split that up:

  • ls -l : Perform a long list of files with ls .
  • grep “Aug” : Select the lines from the list ls with & # 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.

Coupler grep with some regular expressions - fu really takes it to the next level. RELATED: Use regular standard expressions to search better and save time




Source link