grep命令-过滤字符串

常用参数

  • -i 搜索时,忽略大小写

  • -c 只输出匹配行的数量

  • -l 只列出符合匹配的文件名,不列出具体的匹配行

  • -n 列出所有的匹配行,显示行号

  • -h 查询多文件时不显示文件名

  • -s 不显示不存在、没有匹配文本的错误信息

  • -v 显示不包含匹配文本的所有行,即反选

  • -w 匹配整词

  • -x 匹配整行

  • -r 递归搜索

  • -q 禁止输出任何结果,已退出状态表示搜索是否成功

  • -b 打印匹配行距文件头部的偏移量,以字节为单位

  • -o 与-b结合使用,打印匹配的词据文件头部的偏移量,以字节为单位

  • -E 多条件关键字用|隔开

  • -f 查两个文件中的并集(相同部分)

过滤范围可以用 [a-z][0-9] 来表示字母或数字

部分示例

# 不显示所有包含小写字母的内容
grep -v [a-z] filename

# 多个条件,满足一个即可
grep -E "str1|str2" filename

# 过滤出文件中的URL
cat fielname | grep -Eo "(http|https)://[a-zA-Z0-9./=_%:-]*"

# 显示关键字所在行号
grep -n "str" filename

关键字前后指定行 -B (before) -A (after)

cat jpbill.log | grep "2019-10-21" | grep -A 1 -B 1 "Error"

grep 多个关键字 -E

cat filename | grep -E "a|b"

查并集

cat >> 1.txt < EOF
1,hello world
2,hello java
3,hello php
4,hello python
EOF

cat >> 2.txt < EOF
1,hello world
2,hello java
4,hello ruby
5,hello python
EOF

grep -f 1.txt 2.txt
1,hello world
2,hello java

最后更新于