温习之-----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,只显示了行号
原文地址:https://www.cnblogs.com/landhu/p/12362131.html