bash grep

Created

2023-09-12 17:30:16

Updated

2024-10-28 12:37:34

-E/egrep
  1. 不带-E的时候 那么{} () | + ? 没有特别含义,就是它本身,如果想要变成特殊含义则前面加上
  2. 带上-E与之相反
  3. 等价与egrep

1 -v 显示不匹配的行

hello world
python hell
abc hello efg
grep hello 1.txt
# 结果
hello world
abc hello efg
grep hello -v 1.txt
# 结果
python hell

2 忽略大小写

grep -i hello <<EOF
hello world
python hell
abc HeLlo efg
EOF
# 结果
hello world
abc HeLlo efg

3 显示行号

grep -n hello <<EOF
hello world
python hell
abc hello efg
EOF

1:hello world
3:abc hello efg

4 递归搜索

tree
.
├── 1.txt 
└── a
    ├── 1.txt
    └── b
        └── 1.txt
# 会搜索当前目录下的所有文件
grep -r hello # 不能指定文件
    a/b/1.txt:go hello
    a/1.txt:python hello
    1.txt:hello
    1.txt:hello world

# -l 只显示 匹配的文件名
grep -rl hello
    a/b/1.txt
    a/1.txt
    1.txt

5 -F 按字面意思找

grep "he.*" 1.txt
    hello
    hello world
    hell
    he.*
grep "he\.\*" 1.txt
    he.*
grep -F "he.*" 1.txt
    he.*

6 查看匹配行的前后几行

# -A  --after-context
# -B  --before-context
cat example.txt|grep "hello" -A 10 -B 2

7 -c 只显示匹配了几行

grep -c hello 1.txt

8 -w 匹配整词

grep -w hello <<EOF
helloworld
hello world
abchello xzy
EOF

9 -x 匹配到整行

grep -x "hello world" <<EOF
hello world 
hello world
hello world ok
EOF
# 只会匹配到第二行, 第一行 后面有空格 也不行.
Back to top