Linux grep 命令用于查找文件里符合條件的字符串。
grep 指令用于查找內容包含指定的范本樣式的文件,如果發現某文件的內容符合所指定的范本樣式,預設 grep 指令會把含有范本樣式的那一列顯示出來。若不指定任何文件名稱,或是所給予的文件名為 -,則 grep 指令會從標準輸入設備讀取數據。
grep [-abcEFGhHilLnqrsvVwxy][-A<顯示行數>][-B<顯示列數>][-C<顯示列數>][-d<進行動作>][-e<范本樣式>][-f<范本文件>][--help][范本樣式][文件或目錄...]
參數:
1、在當前目錄中,查找后綴有 file 字樣的文件中包含 test 字符串的文件,并打印出該字符串的行。此時,可以使用如下命令:
grep test *file
結果如下所示:
$ 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"的文件,并打印出該字符串所在行的內容,使用的命令為:
grep -r update /etc/acpi
輸出結果如下:
$ 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、反向查找。前面各個例子是查找并打印出符合條件的行,通過"-v"參數可以打印出不符合條件行的內容。
查找文件名中包含 test 的文件中不包含test 的行,此時,使用的命令為:
grep -v test *test*
結果如下所示:
$ 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.