Shell 文本处理三剑客之grep

grep

♦参数

-E,--extended-regexp              模式是扩展正则表达式
-i,--ignore-case                  忽略大小写
-n,--line-number                  打印行号
-v,--invert-match                 打印不匹配的行
-o,--only-matching                只打印匹配的内容
-m,--max-count=NUM               输出匹配的结果 num 数
-c,--count                        只打印每个文件匹配的行数
-r,--recursive                    递归目录 
-w,--word-regexp                  模式匹配整个单词 
--include=FILE_PATTERN             只检索匹配的文件

 ♦示例

1.过滤b文件中与a文件相同的行

[root@gitlab grep]# cat a.txt 
12345
54321
[root@gitlab grep]# cat b.txt 
12345
678910
12345
[root@gitlab grep]# grep -f a.txt b.txt 
12345
12345
[root@gitlab grep]# grep -f b.txt a.txt 
12345
[root@gitlab grep]# 

2.过滤b文件中与a文件不同的行

[root@gitlab grep]# grep -v -f a.txt b.txt 
678910

3.匹配出去空行和以#开头的行

[root@gitlab grep]# grep -E -v "^$|^#" /etc/fstab 

 4.精确匹配

[root@gitlab grep]# echo ” this is a test“ | egrep -w -o 'is'
is

-w 匹配到整个单词 -o 输出匹配到的单词

5.输出匹配的前五个结果

[root@gitlab grep]# seq 1 20 | grep -E -m 5 [0-9]{2}
10
11
12
13
14

 6.统计匹配多少行

[root@gitlab grep]# seq 1 20 | grep -c -E '[0-9]{2}'
11

 7.匹配以b开头的行

# echo "a bc de" |xargs -n1 |grep '^b'

 8.匹配de字符结尾的行,并输出匹配的行号

echo "a ab abc abcd abcde" |xargs -n1 |grep -n 'de$'

 9.

→递归搜索/etc目录下包含UUID的所有文件

[root@gitlab grep]# grep -r 'UUID' /etc --include *

→递归搜索/etc 目录下包含 ip 的 conf 后缀文件

[root@gitlab grep]# grep -r '192.167.1.1' /etc --include *.conf
/etc/ip.conf:192.167.1.1

 10.匹配所有IP

[root@gitlab shell]# ifconfig |grep -E -w -o "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"

 11.杂谈

grep [^#] /data/zabbix/etc/zabbix_server.conf
匹配除了#以外任意的字符
grep ^[^#] /data/zabbix/etc/zabbix_server.conf
过滤出来不是以#开头的行

 

原文地址:https://www.cnblogs.com/charon2/p/10552091.html