Linux之grep的使用

2022-07-24 09:15:07 字數 3020 閱讀 7352

基本介紹

linux系統中grep命令是一種強大的文字搜尋工具,它能使用正規表示式搜尋文字,並把匹 配的行列印出來。grep全稱是global regular expression print,表示全域性正規表示式版本,它的使用許可權是所有使用者。

grep的工作方式是這樣的,它在乙個或多個檔案中搜尋字串模板。如果模板包括空格,則必須被引用,模板後的所有字串被看作檔名。搜尋的結果被送到標準輸出,不影響原檔案內容。

grep可用於shell指令碼,因為grep通過返回乙個狀態值來說明搜尋的狀態,如果模板搜尋成功,則返回0,如果搜尋不成功,則返回1,如果搜尋的檔案不存在,則返回2。我們利用這些返回值就可進行一些自動化的文字處理工作。

表示式

grep [option] pattern file     注意:後面可以跟多個file

引數介紹

規則表示式:

分類

基本使用

示例:

[root@localhost test]# cat test.txt 

hnlinux

peida.cnblogs.com

ubuntu

ubuntu linux

redhat

redhat

linuxmint

[root@localhost test]# cat test2.txt

linux

redhat

命令:cat test.txt | grep -f test2.txt test3.txt

命令:cat test.txt | grep -nf test2.txt

命令:grep 'linux' test.txt test2.txt

命令:grep -w 'linux' test.txt test2.txt

命令:cat test.txt |grep ^[^u]

命令:cat test.txt |grep ^u

命令:cat test.txt |grep hat$

命令:ifconfig eth0|grep "[0-9]\\.[0-9]\\.[0-9]\\.[0-9]\"

結果:inet addr:192.168.120.204  bcast:192.168.120.255  mask:255.255.255.0

命令:ifconfig eth0|grep -e "([0-9]\.)[0-9]"

結果:inet addr:192.168.120.204  bcast:192.168.120.255  mask:255.255.255.0

命令:cat test.txt |grep -e "ed|at"

命令:grep '[a-z]\' *.txt

命令:grep -a 2 "a" test.txt

命令:grep -b 2 "a" test.txt

命令:grep -c 2 "a" test.txt

命令:grep -b "a" test.txt

命令:grep -c "a" test.txt

命令:grep -e "a" -e "1" test.txt

命令:grep -i "a" test1.txt

命令:grep -m 2 "a" test.txt

命令:grep -n -m 2 "a" test.txt

命令:grep -n -o "a" test.txt

命令:grep -r "a" *

命令:grep -v "a" test.txt

命令:grep "abc\|okm" test.txt

命令:grep -wi "abc" test.txt

命令:grep -n --color '[1-3 a-b]' test.txt

命令:grep -n --color  '^.3' test.txt

命令:grep -n --color '3\?' test.txt

命令:grep -n --color '33\?' test.txt

命令:grep -n --color '3\+' test.txt

命令:grep -n --color '3\' test.txt

命令:grep -n --color 'ab‖

23'>ab∥23

ab‖23' test.txtab

‖23'>命令: grep "[mm]ay" test.txtab

‖23'>命令:grep "[a-z][9]d" test.txtab

‖23'>grep -n "^$" test.txt 

命令:ls -l |grep "^d"

命令:ls -l |grep "^d[d]"

命令:ls -l |grpe "^d…..x..x"

命令:grep -e '2|3' test.txt和grep -e '2|3' test.txt和grep -e '2' -e '3' test.txt都是等價的

說明:上面三種命令都是表示或的關係,即,2和3至少包含乙個就是符合條件的

,但是grep -e 'b' -e 'd' test2.txt test1.txt這種寫法中』d『是不生效的,並且會報:grep: d: no such file or directory

命令:cat test.txt |grep '2' |grep '3'

說明:此命令表示必須同時包含2和3才算符合條件

命令:zgrep -a -a10 '19060222332049555917' za-telecom-cashloan-mics-20190602-10.253.*

命令:zgrep -a 'repaytrialbyperiods' za-telecom-cashloan-mics-20190604-10.253.*|grep -e '2019-06-04 2[3-4]' |grep '查無相應的還款計畫,或者已結清'

Linux之grep工具的使用

grep是乙個強大的文字搜素工具,它能使用正規表示式搜尋文字,並把匹配的行列印出來。介紹兩種規範 basic規範 將字元?解釋為字面意思。要表示特殊的意思需要加轉義字元 extended規範 將字元?解釋為特殊的意思。要表示字面意思需要加轉義字元 grep採用basic規範。命令選項 常見的命令選項...

linux中grep的使用

核心 grep的基本操作 grep是一種強大的文字搜尋工具,它能使用正規表示式搜尋文字,並把匹配的行列印出來 選項 a 不要忽略二進位制資料 a 顯示列數 除了顯示符合範本樣式的那一行之外,並顯示該行之後的內容 b 在顯示符合范文樣式的那一行之外,並顯示該行之前的內容。c 計算符合范文樣式的列數 c...

Linux下grep命令的使用!

grep 錨定行的開始 如 grep 匹配所有以grep開頭的行。錨定行的結束 如 grep 匹配所有以grep結尾的行。匹配乙個非換行符的字元 如 gr.p 匹配gr後接乙個任意字元,然後是p。匹配零個或多個先前字元 如 grep 匹配所有乙個或多個空格後緊跟grep的行。一起用代表任意字元。匹配...