How to use the grep command in Linux

Contents

A terminal prompt on a Linux PC.

El Linux grep The command is a string and pattern matching utility that displays the matching lines from multiple files. It also works with pipelined output from other commands. We show you how.

The story behind grep

the grep The command is famous in Linux and Unix circles for three reasons. First, it is tremendously useful. In second place, the the sheer number of options can be overwhelming. In third place, was written overnight to meet a particular need. The first two are very good; the third is slightly off.

Ken Thompson I had extracted the regular phrase search capabilities ed editor (pronounced ee-dee) and created a little program, for your own use, to search text files. Your department head at Bell Labs, Doug Mcilroy, approached Thompson and described the problem to one of his colleagues, Lee McMahon, I was facing.

McMahon was trying to identify the authors of the Federalist Papers through textual analysis. I needed a tool that could search for phrases and strings in text files. Thompson spent about an hour that night making his tool a general utility that others could use and renamed it grep. It took the name of ed command chain g/re/p , que se traduce comobúsqueda global de expresiones regulares”.

You can see Thompson talking for Brian Kernighan about the birth of grep.

Simple searches with grep

To search for a string within a file, pass search term and filename in command line:

grep dave / etc / password en una terminal widnow

Matching lines are displayed. For this case, it's a single line. Matching text is highlighted. This is because in most distributions grep has an alias for:

alias grep = 'grep --colour = auto'

Let's look at the results where there are multiple lines that match. Buscaremos la palabra “A quick way to calculate the average in Excel is to use an option on the ribbon” en un archivo de registro de la aplicación. Because we can't remember if the word is lowercase in the log file, we will use the -i (ignore uppercase and lowercase) option:

grep -i Average geek-1.log

All matching lines are displayed, with matching text highlighted on each.

We can show the lines that do not match using the -v option (reverse match).

grep -v Mem geek-1.log

There is no highlighting because these are the mismatched lines.

We can cause grep be totally silent. The result is passed to the shell as a return value of grep. A result of zero means the string era found, and a result of one means that was not meetings. We can check the return code using the $? special parameters:

grep -q average geek-1.log
echo $?
grep -q systempeaker geek-1.log
echo $?

Recursive searches with grep

To search nested directories and subdirectories, use -r option (recursive). Note that you don't provide a filename on the command line, must provide a path. Aquí estamos buscando en el directorio actual “.” y cualquier subdirectorio:

grep -r -i memfree .

The output includes the directory and filename of each matching line.

We can do grep follow symbolic links using the -R (recursive dereference) option. We have a symbolic link in this directory, called logs-folder. Point to /home/dave/logs.

ls -l logs-folder

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

grep -R -i memfree .

Follow the symbolic link and look for the directory it points to. grep what's more.

Searching for whole words

Default, grep will match a line if the search target appears anywhere on that line, even within another string. Look at this example. Vamos a buscar la palabra “for free”.

grep -i free geek-1.log

Los resultados son líneas que disponen la cadenalibreen ellas, but they are not separate words. Forman parte de la cadenaMemFree”.

To force grep para hacer coincidir solo “words” separadas, Use the -w (word regexp) option.

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

Esta vez no hay resultados debido a que el término de búsqueda “for free” no aparece en el archivo como una palabra separada.

Using multiple search terms

the -E (extended regular expression) enables you to search multiple words. (The -E option replace the obsolete egrep version of grep.)

This command searches for two search terms, “promedio” 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.

the -e The option (patterns) enables you to use multiple search terms on the command line. We are using the regex brackets function to create a search pattern. Dice grep para que coincida con cualquiera de los caracteres incluidos entre corchetes “[]. ” This means grep will match "kB" or "KB" while searching.

Both strings match and, actually, some lines contain both strings.

Exact match of lines

the -x (line regexp) will only match the lines where the complete line matches the search term. Let's look for a timestamp that we know appears only once in the log file:

grep -x "20-Jan--06 15:24:35" geek-1.log

The only line that matches is found and displayed.

The opposite of that is just showing the lines that no match. This can be useful when looking for configuration files. The comments are great, but from time to time it is difficult to identify the real configuration between all of them. Here is the /etc/sudoers proceedings:

We can effectively filter the comment lines this way:

sudo grep -v "#" /etc/sudoers

That is much easier to analyze.

Only matching text display

There may be a time when you don't want to see the entire matching line, just the matching text. the -o The option (only match) does exactly that.

grep -o MemFree geek-1.log

The screen is reduced to showing only the text that matches the search term, instead of the whole matching line.

Counting on grep

grep it's not just about text, it can also provide numerical information. We can do grep counts for us in different ways. If we want to know how many times a search definition appears in a file, we can use the -c (count) option.

grep -c average geek-1.log

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

Can you do grep display the line number for each matching line using the -n option (line number).

grep -n Jan geek-1.log

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

To reduce the number of results displayed, Use the -m (maximum count) option. We are going to limit the output to five matching lines:

grep -m5 -n Jan geek-1.log

Add context

It is often helpful to be able to see a few extra lines, possibly mismatched lines, for each matching line. can help you distinguish which of the matching lines are the ones you are interested in.

To show some lines after the matching line, use the -A option (after context). We are requesting three lines in this example:

grep -A 3 -x "20-Jan-06 15:24:35" geek-1.log

To see some lines before the matching line, use el -B (context before) option.

grep -B 3 -x "20-Jan-06 15:24:35" geek-1.log

And to include lines before and after the matching line, use el -C (context) option.

grep -C 3 -x "20-Jan-06 15:24:35" geek-1.log

Show matching files

To view the names of the files that contain the search term, use the -l (matched files) option. To find out which C source files contain references to the sl.h header file, use this command:

grep -l "sl.h" *.c

File names are listed, not the matching lines.

AND, decidedly, we can search for files that do not contain the search term. the -L The option (unmatched files) does exactly that.

grep -L "sl.h" *.c

Start and end of lines

We can force grep to show only matches that are at the beginning or end of a line. The regular expression operator "^" matches the beginning of a line. Virtually all lines within the log file will contain spaces, but we will look for lines that have a space as the first character:

grep "^ " geek-1.log

Lines that have a space as the first character are displayed, at the beginning of the line.

To match the end of the line, use el operador de expresión regular “$”. Vamos a buscar líneas que terminen con “00”.

grep "00$" geek-1.log

La pantalla muestra las líneas que disponen “00” como caracteres finales.

Using Pipes with grep

Decidedly, can funnel input to grep , pipe the output of grep in another program and have grep nestled in the middle of a chain of pipes.

Digamos que queremos ver todas las apariciones de la cadena “ExtractParameters” en nuestros archivos de código fuente C. We know there will be quite a few, so we channel the output to less:

grep "ExtractParameters" *.c | less

The output is presented in less.

This enables you to browse the list of files and use less's ease of search.

If we channel the output of grep within wc and use the -l (lines) option, us can count the number of lines en los archivos de código fuente que contienen “ExtractParameters”. (We could achieve this using the grep -c (count) option, but this is a nice way to demonstrate the pipe outside grep.)

grep "ExtractParameters" *.c | wc -l

With the following command, we are channeling the output of ls within grep and channeling the output of grep within sort . We are listing the files in the current directory, seleccionando aquellos con la cadena “Aug” You don't need to add the extension, and sorting them by file size:

ls -l | grep "Aug" | sort +4n

Let's analyze that:

  • ls -l: Make a long format list of files using ls.
  • grep “agosto: Select the lines of the ls listado que tiene “Aug” You don't need to add the extension. Tenga en cuenta que esto además encontrará archivos que tengan “Aug” en sus nombres.
  • order + 4n: Sort the output of grep in the fourth column ().

We get an ordered list of all files modified in August (regardless of the year), in ascending order of file size.

RELATED: How to use Pipes on Linux

grep: Minus one command, plus an ally

grep is a great tool to have at your disposal. On the 1974 and it still stands strong because we need what it does, and nothing makes it better.

Coupling grep with some regex, fu truly takes it to the next level.

RELATED: How to use basic regular expressions to search better and save time

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.