shell指令碼 內容查詢之grep命令

2022-03-19 00:11:22 字數 2693 閱讀 4600

grep命令可以檢索檔案中包含關鍵字(可以使用正則)的行,預設區分大小寫。

ubuntu@ubuntu:~/test$ cat test.txt

this is linux

this is linux

this is mysql

this is mysql

ubuntu@ubuntu:~/test$ grep 'linux' test.txt

this is linux

ubuntu@ubuntu:~/test$ grep 'mysql' test.txt

this is mysql

ubuntu@ubuntu:~/test$

使用 -c 引數,獲取包含關鍵字的行數

ubuntu@ubuntu:~/test$ grep -c 'is' test.txt

4ubuntu@ubuntu:~/test$ grep -c 'sql' test.txt

2ubuntu@ubuntu:~/test$

使用 -n 引數,列印內容的同時,顯示所在的行號

ubuntu@ubuntu:~/test$ cat test.txt

this is linux

this is linux

this is mysql

this is mysql

ubuntu@ubuntu:~/test$ grep -n 'mysql' test.txt

3:this is mysql

ubuntu@ubuntu:~/test$

使用 -i 引數,查詢時,不區分大小寫

ubuntu@ubuntu:~/test$ grep -i 'mysql' test.txt

this is mysql

this is mysql

ubuntu@ubuntu:~/test$

使用 -v 引數,查詢不包含關鍵字的行(反向查詢)

ubuntu@ubuntu:~/test$ cat test.txt

this is linux

this is linux

this is mysql

this is mysql

ubuntu@ubuntu:~/test$ grep -v 'linux' test.txt

this is linux

this is mysql

this is mysql

ubuntu@ubuntu:~/test$

使用 -e 引數,可以同時指定多個篩選條件

ubuntu@ubuntu:~$ cat test.txt 

this is a

this is b

three are a and b

ubuntu@ubuntu:~$ grep "a" test.txt | grep "this" #與關係,包含a,並且包含this

this is a

ubuntu@ubuntu:~$ grep -e "a" -e "this" test.txt #或關係,包含a或者包含this

this is a

this is b

three are a and b

要想使用正規表示式,可以使用 -e 引數

shell正則和perl語言的正則類似,基本通用。

ubuntu@ubuntu:~/test$ cat test.txt

this is linux

this is linux

ubuntu@ubuntu:~/test$ grep -e '^that' test.txt #以that開頭的行

ubuntu@ubuntu:~/test$ grep -e 'linux$' test.txt #以linux結尾的行

this is linux

ubuntu@ubuntu:~/test$ grep -e '.inux' test.txt # '.'表示任意乙個字元(不包含空白)

this is linux

this is linux

ubuntu@ubuntu:~/test$ grep -e 'p*' test.txt # 『*』表示前面乙個字母出現0,1或任意多次

this is linux

this is linux

ubuntu@ubuntu:~/test$ grep -e '.+p.+' test.txt # 『+』表示前面乙個字母出現1或任意多次

ubuntu@ubuntu:~/test$ grep -e 'p' test.txt # 前面的乙個字元出現n次

ubuntu@ubuntu:~/test$

還有一些常用的匹配模式,比如 '^$'表示乙個空行 ;   '^.$'表示只有乙個字元的行  ; 使用 \ 來轉義,比如使用\.來匹配乙個點   ; [0-9]表示匹配乙個數字 ; [a-z]|[a-z]表示任意乙個字母; 使用|表示『或』  ;

ubuntu@ubuntu:~/test$ echo 'ip is 192.168.1.1' > test.txt

ubuntu@ubuntu:~/test$ grep -e '([1-9][0-9]*\.)[1-9][0-9]*' test.txt

ip is 192.168.1.1

ubuntu@ubuntu:~/test$

shell指令碼設計之檔案查詢

判斷目錄 root mmm 下是否存在乙個名為1.c的檔案,如果存在,將它改名為111.c 如果不存在,顯示一行資訊 root mmm 1.c does not exit報告這個檔案不存在。在查詢存在的檔案 root mmm cba.c並將其改名為abc.c,儲存目錄保持不變。查詢不存在的檔案並提示...

shell指令碼之查詢與替換 一

文字查詢 searching 與文字替換 substitution 是編寫shell指令碼時經常用到的兩個基本操作。查詢文字 傳統上,有三種程式可以用來查詢整個文字檔案 grep,egrep extended grep fgrep fast grep grep最簡單的用法就是使用固定字串,例如who...

shell 指令碼之for

subdir joan joanna for subdir in subdir doecho building subdir done 結果 building joan building joanna 結果正常。subdir 1 2 3 4 for subdir in subdir doecho b...