Linux常用命令 二 grep命令

2021-08-28 11:46:44 字數 1901 閱讀 3144

linux grep命令用於查詢檔案裡符合條件的字串。

grep指令用於查詢內容包含指定的範本樣式的檔案,如果發現某檔案的內容符合所指定的範本樣式,預設grep指令會把含有範本樣式的那一列顯示出來。若不指定任何檔名稱,或是所給予的檔名為"-",則grep指令會從標準輸入裝置讀取資料。

grep [-abcefghhillnqrsvvwxy][-a《顯示列數》][-b《顯示列數》][-c《顯示列數》][-d《進行動作》][-e《範本樣式》][-f《範本檔案》][--help][範本樣式][檔案或目錄...]
引數

grep -c host *-error.log

grep -c10 host *-error.log 

grep -i host *-error.log

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.

**

Linux常用命令grep

所有的類linux系統都會提供乙個名為grep global regular expression print,全域性正規表示式輸出 的搜尋工具。grep命令在對乙個或多個檔案的內容進行基於模式的搜尋的情況下是非常有用的。模式可以是單個字元 多個字元 單個單詞 或者是乙個句子。當命令匹配到執行命令時...

Linux常用命令 grep命令

linux grep 命令用於查詢檔案裡符合條件的字串 grep 指令用於查詢內容包含指定的範本樣式的檔案,如果發現某檔案的內容符合所指定的範本樣式,預設 grep 指令會把含有範本樣式的那一列顯示出來。若不指定任何檔名稱,或是所給予的檔名為 則 grep 指令會從標準輸入裝置讀取資料。grep r...

Linux常用命令 grep命令

root grep action color auto 搜尋字串 filename 選項與引數 a 講binary 檔案以 text 檔案的方式搜尋資料 c 計算找到 搜尋字串 的次數 i 忽略大小寫的不同,所以大小寫視為相同 n 順便輸出行號 v 反向選擇,亦即顯示出沒有 搜尋字串 內容的那一行 ...