grep

一 grep 是干什么的

  grep (缩写来自Globally search a Regular Expression and Print)是一种强大的文本搜索工具,它能使用特定模式匹配(包括正则表达式)搜索文本,并默认输出匹配行。

二 grep 语法

  grep [ -acinv ] [ -A]  [ -B ]  [ --color=auto ]  ' 查找字符串 '  filename

  参数

    -a:将binary文件已text文件的方式查找数据

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -a 'UP'
UPower

    -c:计算找到 “查找字符串” 的次数

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -c 'UP'
1

    -i:忽略大小写

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -i 'UP'
backup
centos-release-upstream
cups
cupshelpers
gnupg
group
group-
setuptool.d
updatedb.conf
UPower
wpa_supplicant

    -n:出处行号

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -n 'UP'
289:UPower

    -v:反向选择,即显示没有“查找字符串”内容的那一行

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -v 'UP'
abrt
adjtime
aliases
aliases.db
alsa
alternatives
... ...

    -A:后面可加数字,为after的意思,除了列出该行外,后续的 n 行 也列出来。

    -B:后面可加数字,为before的意思,除了列出该行外,前面的 n 行也列出来。

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls -al
total 2084
... ...
drwxr-xr-x    2 root  root     4096 Jun 20 02:56 udisks2
drwxr-xr-x    2 root  root     4096 Jun 20 02:55 unbound
-rw-r--r--    1 root  root      163 Jun 13 16:23 .updated
-rw-r--r--    1 root  root      557 Apr 11 04:32 updatedb.conf
drwxr-xr-x    2 root  root     4096 Jun 20 02:55 UPower
-rw-r--r--    1 root  root     1523 Apr 11 07:48 usb_modeswitch.conf
-rw-r--r--.   1 root  root       37 Oct 15  2017 vconsole.conf
-rw-r--r--    1 root  root     1982 Apr 11 07:54 vimrc
... ...

  的确如此。但是 隐藏文件并不包含在数字中。

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -A 2 -B 3 'UP' 
udisks2
unbound
updatedb.conf
UPower
usb_modeswitch.conf
vconsole.conf
原文地址:https://www.cnblogs.com/654321cc/p/9281061.html