penglongli / blog

18 stars 1 forks source link

Linux 下的 grep 命令 #35

Open penglongli opened 6 years ago

penglongli commented 6 years ago

grep 命令太强大了,再加上现实需求是多变的,本文只介绍实例

单文件查询

查询单个文件(区分大小写):

root@host-1:~# grep 'root' /etc/passwd

增加 -i 参数忽略大小写:

root@host-1:~# grep -i 'Root' /etc/passwd

递归查询

主要用到了 -R-r 参数,两者有一个简单的不同之处。

root@host-1:~/test# touch t1.txt
root@host-1:~/test# echo "111111 22222" > t1.txt
root@host-1:~/test# grep -r "1" ./

我们在最后一个参数增加了当前目录,如果没有这个参数则默认使用当前目录(建议:如果要查找当前目录,务必加上这个参数

-R-r 的区别

在要查询的目标目录下,有文件是软连得到的,则 -r 参数会忽略这个文件。

扩展

经常与 -n 参数联合使用,可以显示行号

精确查找单词

注意:这里是指单词,也只能是单词

root@host-1:~/test# echo "abcd-efg" > t1.txt
# 此查询无任何结果
root@host-1:~/test# grep -w "ab" t1.txt
# 此查询有结果
root@host-1:~/test# grep -w "abcd" t1.txt
abcd-efg

扩展:不要被表象迷惑

root@host-1:~/test# echo "test" > t1.txt
root@host-1:~/test# echo "test-old" >> t1.txt
root@host-1:~/test#
root@host-1:~/test# grep -w "test" t1.txt
test
test-old

可以发现,查出来了两个结果。

正确的做法:

$ grep -w "test$" t1.txt

查找 2 个不同的单词

root@host-1:~/test# egrep -w "word1|word2" test.txt

查找匹配到的数量

root@host-1:~/test# grep -c 'word' test.txt

反向匹配

反向匹配按行查找,如果一行没有能匹配到的数据,则反向匹配成功。

root@host-1:~/test# grep -v "aaaaa" test.txt

查找包含匹配格式的文件

oot@host-1:~/test# grep -l 'test' *.txt

查找当前目录下所有内容包含 test 的 .txt 后缀的文件

查找文件行数

使用 -c 来查找一个文件或多个文件的行数,下述能打印出来每个文件的行数

root@host-1:~/test# grep -c "$" *.txt
test1.txt:2
test.txt:3

扩展: 递归查询所有 *.java 后缀的行数之和

$ grep -rc "$" ./ | grep "\.java" | awk -F: '{print $NF}' | awk '{sum += $1} END {print sum}'
3193

简单说明下上述脚本:首先根据结尾符 "$" 递归统计当前目录下所有文件的行数,然后筛选出来 java 后缀的文件,然后使用 awk 以 “:” 为分隔符输出最后一列的数值,然后使用 awk 累加并输出结果。

(脚本存在的问题:先获取了所有文件的行数。这一步其实做了无用功)

实例