linux指令 grep,【linux命令之grep】

grep(global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)

是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

1. 常用用法

#在文件中搜索一个单词,命令会返回一个包含“match_pattern”的文本行

grep match_pattern file

或者

grep "match_pattern" file

2. 在多个文件中查找

grep "match_pattern" file1 file2 file3 ...

3. 输出除之外的所有行 -v 选项

grep -v "match_pattern" file

4. 标记匹配颜色 --color=auto 选项

grep "match_pattern" file_name --color=auto

5.只输出文件中匹配到的部分 -o 选项

echo this is a test line. | grep -o -E "[a-z]+\."

输出:line.

echo this is a test line. | egrep -o "[a-z]+\."

输出:line.

6. 使用正则表达式 -E 选项

grep -E "[1-9]+"

egrep "[1-9]+"

7.统计文件或者文本中包含匹配字符串的行数 -c 选项

grep -c "text" file

8.输出包含匹配字符串的行号 -n 选项

grep -n "text" file

cat file_name | grep "text" -n

#多个文件

grep "text" -n file1 file2

9. 打印样式匹配所位于的字符或字节偏移

echo gun is not unix | grep -b -o "not"

输出:7:not

一行中字符串的字符偏移是从该行的第一个字符开始计算,起始值为0。选项 -b -o 一般总是配合使用

10. 搜索多个文件并查找匹配文本在哪些文件中

grep -l "text" file1 file2 file3...

#不在哪些文件中用大写L

grep -L "text" file1 file2 file3...

#匹配多个文件不显示文件名(大写H显示文件名)

grep -h "text" file1 file2 file3...

11. grep递归搜索文件 .标识当前目录

grep "text" . -r -n

12. 忽略匹配样式中的字符大小写

echo "hello world" | grep -i "HELLO"

输出:hello world

13. 选项 -e 制动多个匹配样式

echo this is a text line | grep -e "is" -e "line" -o

输出:

is

is

line

也可以使用-f选项来匹配多个样式,在样式文件中逐行写出需要匹配的字符

cat patfile

aaa

bbb

echo aaa bbb ccc ddd eee | grep -f patfile -o

也可以用

echo this is a text line | grep -E "is|line" -o

14. 输出开头/结尾的行内容

#找出A开头的行内容

cat file1 | grep ^A

#找出非A开头的行内容

cat file1 | grep ^[^A]

#找出A结尾的行内容

cat file1 | grep A$

15. 打印出匹配文本之前或者之后的行

#显示匹配某个结果之后的3行,使用 -A 选项:

seq 10 | grep "5" -A 3

输出:

5

6

7

8

#显示匹配某个结果之前的3行,使用 -B 选项:

seq 10 | grep "5" -B 3

输出:

2

3

4

5

#显示匹配某个结果的前三行和后三行,使用 -C 选项:

seq 10 | grep "5" -C 3

输出:

2

3

4

5

6

7

8

#如果匹配结果有多个,会用“--”作为各匹配结果之间的分隔符:

echo -e "a\nb\nc\na\nb\nc" | grep a -A 1

输出:

a

b

--

a

b

喜欢的打赏支持哦 ^ ~ ^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值