文本三剑客之grep

169 阅读1分钟

grep简介

grep 是一个过滤器,在文件中查找符合条件的内容,包含指定关键字的内容或者字符串的内容。 image.png image.png image.png

1、 grep ‘字符串

image.png

2、 反向匹配grep -v ‘字符串

image.png

3、 grep -E 同时匹配多个关键字

image.png

4、 同时匹配多个关键字

image.png

5、显示前几行和后几行

image.png

image.png

image.png

image.png image.png image.png image.png image.png image.png image.png image.png

小练习

利用df和grep,取出磁盘各分区利用率,并从大到小排序
df |grep "^/dev/sd"|egrep -o '[[:digit:]]+%'|tr -d % |sort -nr
 
找出/etc/passwd用户名和shell同名的行
egrep "^([^:]+):.*\<\1$" /etc/passwd
egrep  -o "^(.*)(:.*)\<\1$"  /etc/passwd
 
取出ifconfig eth0的ip
ifconfig ens33 | egrep -o "([0-9]{1,3}.){3}[0-9]{1,3}"
 
取出ss.log日志中排名前三的ip地址
grep "^ESTAB" ss.log | tr -s ' ' :| cut -d: -f6|sort|uniq -c|sort -nr |head -3
 
将此字符串:welcome to magedu linux 中的每个字符去重并排序,重复次数多的排到前⾯
echo wecome to magedu linux | grep -o "."|sort|uniq -c |sort -nr
 
使⽤egrep取出/etc/rc.d/init.d/functions路径的⽬录名
echo /etc/rc.d/init.d/functions|egrep -o "^[/].*/"
 
计算年龄总和:
cat age.txt
xiaoming=20
xiaohong=18
xiaoqiang=22
 
cut -d= -f2 age.txt |tr -s "\n" +|egrep -o ".*[0-9]+" |bc
60