Linux grep command


  Translation results:

grep

UK ['grep] US ['grep]

[Calculation] Retrieve target line command

Linux grep commandsyntax

Function: The grep command is used to find strings that meet the conditions in the file.

Syntax: grep [-abcEFGhHilLnqrsvVwxy][-A<Display number of columns>][-B<Display number of columns>][-C<Display number of columns>][ -d<Perform Action>][-e<Template Style>][-f<Template File>][--help][Template Style][File or Directory...]

Linux grep commandexample

1. In the current directory, find the file containing the test string in the file with the word file suffixed, and print out the line of the string. At this time, you can use the following command:

grep test *file

The result is as follows:

$ grep test test* #查找前缀有“test”的文件包含“test”字符串的文件  
testfile1:This a Linux testfile! #列出testfile1 文件中包含test字符的行  
testfile_2:This is a linux testfile! #列出testfile_2 文件中包含test字符的行  
testfile_2:Linux test #列出testfile_2 文件中包含test字符的行

2. Search for files that meet the conditions recursively. For example, to find files containing the string "update" in all files in the specified directory /etc/acpi and its subdirectories (if subdirectories exist), and print out the content of the line where the string is located, the command used is:

grep -r update /etc/acpi

The output results are as follows:

$ grep -r update /etc/acpi #以递归的方式查找“etc/acpi”  #下包含“update”的文件  
/etc/acpi/ac.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of IO.)  Rather than  
/etc/acpi/resume.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of  
IO.) Rather than  
/etc/acpi/events/thinkpad-cmos:action=/usr/sbin/thinkpad-keys--update

3. Reverse search. The previous examples are to find and print out the lines that meet the conditions. The "-v" parameter can be used to print out the contents of the lines that do not meet the conditions.

Find the lines that do not contain test in the files whose file names contain test. At this time, the command used is:

grep -v test *test*

The result is as follows:

$ grep-v test* #查找文件名中包含test 的文件中不包含test 的行  
testfile1:helLinux!  
testfile1:Linis a free Unix-type operating system.  
testfile1:Lin  
testfile_1:HELLO LINUX!  
testfile_1:LINUX IS A FREE UNIX-TYPE OPTERATING SYSTEM.  
testfile_1:THIS IS A LINUX TESTFILE!  
testfile_2:HELLO LINUX!  
testfile_2:Linux is a free unix-type opterating system.

Popular Recommendations

Home

Videos

Q&A