溫習之-----grep 中各參數


今天看見一小伙伴,在用grep中總是喜歡加上-a參數,問他-a是什么意思,他說不知道,看到別人是這么用的......

沒辦法,只好再次將grep再給他講了一編。

首先來解決下-a是什么意思,還是看官網吧:

-a, --text
              Process a binary file as if it were text; this is equivalent to the --binary-files=text option.

解釋一下,-a就是說明在文件是二進制文件時才使用,所以不是二進制的文件就沒必要用這個-a的參數。

如果是二進制文件文件不加-a是怎么樣呢?

[root@controller2 bin]# grep fini_array zip
Binary file zip matches

然后,我們再加加-a看看是怎么樣的

[root@controller2 bin]# grep -a fini_array zip
ᕚG¿'«uº6Q¼ĶƧ⼢嶫I὆®k}撋I¬ၲ°Hƌb±ç㘚.shstrtab.interp.note.ABI-tag.note.gnu.build-id.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.text.fini.rodata.eh_frame_hdr.eh_frame.init_array.fini_array.jcr.dynamic.got.got.plt.data.bss.gnu_debuglink.gnu_debugdata
               8@8T@T !t@t$4ྯ@>

這就很好說明了二進制文件要用-a,但我想一般工作,我們很少去看二進制文件吧。所以這個參數基本可以忽略。

 

接下來,我們再來溫習下grep的其它參數:

這里,我只列出常用的參數:

-c 只輸出匹配行的計數。
-i 不區分大小寫(只適用於單字符)。
-h 查詢多文件時不顯示文件名。
-l 查詢多文件時只輸出包含匹配字符的文件名。
-n 顯示匹配行及行號。
-s 不顯示不存在或無匹配文本的錯誤信息。
-v 顯示不包含匹配文本的所有行。

 

一個一個來舉實例說明吧,這里還是拿萬能的/etc/passwd文件來測試吧

[root@rdf etc]# grep -c root /etc/passwd
2

 

[root@controller2 etc]# grep -c ROOT /etc/passwd
0
[root@controller2 etc]# grep -ci ROOT /etc/passwd
2

第一行先用大寫的查找一下,第二條命令加了-i,不區分大小寫
[root@controller2 etc]# grep -ni ROOT /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
10:operator:x:11:0:operator:/root:/sbin/nologin
[root@xfd etc]# grep  ROOT /etc/passwdd
grep: /etc/passwdd: No such file or directory


這是一個不存在的文件,結果有錯誤信息顯示

加-s會怎么樣?
[root@xfd etc]# grep -s ROOT /etc/passwdd
[root@xfd etc]#

但是返回的錯誤碼也是一致的
[root@xfd etc]# echo $?
2
[root@controller2 etc]# grep  -ivc ROOT /etc/passwd
58

加了-v是反選
-h  和-l 一般與-r匹配着使用,查找某個文件夾下的多個文件,但感覺是雞肋,如下
[root@xfd etc]# grep  -ivclr ROOT /etc/|more
/etc/fstab
/etc/resolv.conf
/etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
/etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-Debug-7

這是加了-l,只顯示文件名

[root@xfd etc]# grep  -ivchr ROOT /etc/|more
11
0
2

這里加了-h,只顯示了行號

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM