Linux安全基础:grep命令的使用
grep (縮寫來自Globally search a Regular Expression and Print)是一種強大的文本搜索工具,它能使用正則表達式搜索文本,并把匹配的行打印出來。Unix的grep家族包括grep、egrep和fgrep。
grep的工作方式是這樣的,它在一個或多個文件中搜索字符串模板。如果模板包括空格,則必須被引用,模板后的所有字符串被看作文件名。搜索的結果被送到標準輸出,不影響原文件內容。
1.命令格式:
grep [option] pattern file
2.命令功能:
用于過濾/搜索的特定字符。可使用正則表達式能多種命令配合使用,使用上十分靈活 。
3.命令參數:
-a --text #不要忽略二進制的數據。
-A<顯示行數> --after-context=<顯示行數> #除了顯示符合范本樣式的那一列之外,并顯示該行之后的內容。
-b --byte-offset #在顯示符合樣式的那一行之前,標示出該行第一個字符的編號。
-B<顯示行數> --before-context=<顯示行數> #除了顯示符合樣式的那一行之外,并顯示該行之前的內容。
-c --count #計算符合樣式的列數。
-C<顯示行數> --context=<顯示行數>或-<顯示行數> #除了顯示符合樣式的那一行之外,并顯示該行之前后的內容。?
-d <動作> --directories=<動作> #當指定要查找的是目錄而非文件時,必須使用這項參數,否則grep指令將回報信息并停止動作。?
-e<范本樣式> --regexp=<范本樣式> #指定字符串做為查找文件內容的樣式。
-E --extended-regexp #將樣式為延伸的普通表示法來使用。
-f<規則文件> --file=<規則文件> #指定規則文件,其內容含有一個或多個規則樣式,讓grep查找符合規則條件的文件內容,格式為每行一個規則樣式。
-F --fixed-regexp #將樣式視為固定字符串的列表。
-G --basic-regexp #將樣式視為普通的表示法來使用。
-h --no-filename #在顯示符合樣式的那一行之前,不標示該行所屬的文件名稱。
-H --with-filename #在顯示符合樣式的那一行之前,表示該行所屬的文件名稱。
-i --ignore-case #忽略字符大小寫的差別。
-l --file-with-matches #列出文件內容符合指定的樣式的文件名稱。
-L --files-without-match #列出文件內容不符合指定的樣式的文件名稱。
-n --line-number #在顯示符合樣式的那一行之前,標示出該行的列數編號。
-q --quiet或--silent #不顯示任何信息。
-r --recursive #此參數的效果和指定“-d recurse”參數相同。
-s --no-messages #不顯示錯誤信息。
-v --revert-match #顯示不包含匹配文本的所有行。
-V --version #顯示版本信息。
-w --word-regexp #只顯示全字符合的列。
-x --line-regexp #只顯示全列符合的列。
-y #此參數的效果和指定“-i”參數相同。
4.使用實例
案例1:精確的匹配
[root@localhost ~]# cat 1.txt | grep all all tooall to alltoall all allto100 uuualltoall [root@localhost ~]# cat 1.txt | grep -w "all" all tooall to alltoall all [root@localhost ~]#?
案例2:加入自動顏色
[root@localhost ~]# cat 1.txt | grep -w "all" --color=auto all tooall to alltoall all?
案例3 :取反參數 -v 選項
[root@localhost ~]# ps -ef | grep ssh root 2055 1 0 09:03 ? 00:00:00 /usr/sbin/sshd root 24498 2055 0 11:21 ? 00:00:01 sshd: root@pts/0 root 24657 24502 0 12:11 pts/0 00:00:00 grep ssh [root@localhost ~]# ps -ef | grep ssh | grep -v grep root 2055 1 0 09:03 ? 00:00:00 /usr/sbin/sshd root 24498 2055 0 11:21 ? 00:00:01 sshd: root@pts/0 [root@localhost ~]#?
案例4 :統計出現的次數
[root@localhost ~]# grep -c "all" 1.txt 4 [root@localhost ~]#?
案例5:顯示匹配的行數
[root@localhost ~]# grep -n "all" 1.txt 1:all tooall 2:to alltoall all 3:allto100 4:uuualltoal?
案例6:顯示匹配的文件
[root@localhost ~]# grep "all" 1.txt 2.txt 4.txt 1.txt:all tooall 1.txt:to alltoall all 1.txt:allto100 1.txt:uuualltoall 2.txt:alltohell 2.txt 4.txt:allheot4.txt [root@localhost ~]# grep -l "all" 1.txt 2.txt 4.txt 1.txt 2.txt 4.tx?
案例7:忽略字符大小寫
[root@localhost ~]# cat 1.txt | grep -i "ALL" all tooall ALAALLL to alltoall all allto100 uuualltoall?
案例8:打印出匹配文本之前或者之后的行
?
轉載于:https://www.cnblogs.com/BaoLeri/p/5946080.html
總結
以上是生活随笔為你收集整理的Linux安全基础:grep命令的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 15个开发者最亲睐的Android代
- 下一篇: 输入输出优化