Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来。grep全称是Global Regular Expression Print,表示全局正则表达式版本,它的使用权限是所有用户。
-A 数字N 找到所有的匹配行,并显示匹配行后N行
-B 数字N 找到所有的匹配行,并显示匹配行前面N行
-c 显示与之匹配的行数
-m 数字N 最多匹配后面N项
-i 忽略大小写
[root@node1 abang]# cat hello1
b124230
b034325
a081016
a022021
a061048
[root@node1 abang]# cat hello1 |grep -A 2 b034325
b034325
a081016
a022021
[root@node1 abang]# cat hello1 |grep -B 3 a061048
b034325
a081016
a022021
a061048
[root@node1 abang]# cat hello1 |grep -c a0
3
[root@node1 abang]# cat hello1 |grep -m 2 a0
a081016
a022021
[root@node1 abang]#cat hello1 |grep -i A022021
a022021
反向查找,通过"-v"参数可以打印出不符合条件行的内容
cat yum/version-groups.conf |grep -v '#'
[root@node1 etc]# cat yum/version-groups.conf
# This file allows you to create "groups" of package names, which are used by
# the version command.
[yum]
# These are the top level things to do with yum, we don't list Eg. libselinux
# even though that's require by rpm(-libs).
run_with_packages = true
pkglist = glibc, sqlite, libcurl, nss,
yum-metadata-parser,
rpm, rpm-libs, rpm-python,
python,
python-iniparse, python-urlgrabber, python-pycurl
[root@node1 etc]# cat yum/version-groups.conf |grep -v '#'
[yum]
run_with_packages = true
pkglist = glibc, sqlite, libcurl, nss,
yum-metadata-parser,
rpm, rpm-libs, rpm-python,
python,
python-iniparse, python-urlgrabber, python-pycurl
[root@node1 etc]#
以递归的方式查找符合条件的文件。例如,查找指定目录/etc/yum及其子目录(如果存在子目录的话)下所有文件中包含字符串"yum-metadata-parser"的文件,并打印出该字符串所在行的内容,在/etc目录下使用的命令为:
grep -r yum-metadata-parser ./
[root@node1 etc]# cat yum/version-groups.conf
# This file allows you to create "groups" of package names, which are used by
# the version command.
[yum]
# These are the top level things to do with yum, we don't list Eg. libselinux
# even though that's require by rpm(-libs).
run_with_packages = true
pkglist = glibc, sqlite, libcurl, nss,
yum-metadata-parser,
rpm, rpm-libs, rpm-python,
python,
python-iniparse, python-urlgrabber, python-pycurl
[root@node1 etc]# grep -r yum-metadata-parser ./
./yum/version-groups.conf: yum-metadata-parser,
[root@node1 etc]#