grep

英 ['grep]? ?美 ['grep]??

[計(jì)] 擷取目標(biāo)列指令

Linux grep指令 語(yǔ)法

作用:grep指令用來(lái)尋找檔案裡符合條件的字串。

語(yǔ)法:grep [-abcEFGhHilLnqrsvVwxy][-A<顯示列數(shù)>][-B<顯示列數(shù)>][-C<顯示列數(shù)>][ -d<進(jìn)行動(dòng)作>][-e<範(fàn)本>][-f<範(fàn)本文件>][--help][範(fàn)本樣式][檔案或目錄...]

#

Linux grep指令 範(fàn)例

1、在目前目錄中,尋找後綴有 file 字樣的檔案中包含 test 字串的文件,並列印出該字串的行。此時(shí),可以使用以下命令:

grep test *file

結(jié)果如下所示:

$ 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、以遞歸的方式尋找符合條件的檔案。例如,尋找指定目錄/etc/acpi 及其子目錄(如果存在子目錄的話)下所有文件中包含字串"update"的文件,並列印出該字串所在行的內(nèi)容,使用的命令為:

grep -r update /etc/acpi

輸出結(jié)果如下:

$ 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、反向查找。前面各範(fàn)??例是找出並列印出符合條件的行,透過(guò)"-v"參數(shù)可以列印出不符合條件行的內(nèi)容。

尋找檔案名稱(chēng)中包含 test 的檔案中不包含test 的行,此時(shí),使用的指令為:

grep -v test *test*

結(jié)果如下所示:

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