欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linux用grep匹配多个关键词,并显示前几行或者后面几行的内容

程序员文章站 2022-07-12 15:09:24
...

1、grep过滤多个关键词并输出内容

grep "key1" file.txt |grep "key2" |grep "key3"

grep “key1” file.txt |grep “key2” |grep “key3”

2、grep过滤多个关键词并输出前10行内容

grep "key1" file.txt |grep "key2" |grep "key3" |head -n 10

grep “key1” file.txt |grep “key2” |grep “key3” |head -n 10

3、grep过滤多个关键词并输出后10行内容

grep "key1" file.txt |grep "key2" |grep "key3"|tail -n 10

grep “key1” file.txt |grep “key2” |grep “key3”|tail -n 10

4、grep过滤多个关键词并输出10~20行内容

grep "key1" file.txt |grep "key2" |grep "key3"|head -n 20 |tail -n 10

grep “key1” file.txt |grep “key2” |grep “key3”|head -n 20 |tail -n 10

输出7~13

grep “key1” file.txt |grep “key2” |grep “key3”|head -n 13 |tail -n 5
在输出前面13行的内容前提基础下,再输出后面5行内容(13-7=5),就是输出7~13的内容了

5、grep过滤多个关键词并输出10~20行内容到文件test.txt

grep "key1" file.txt |grep "key2" |grep "key3"|head -n 20 |tail -n 10 >> test.txt

grep “key1” file.txt |grep “key2” |grep “key3”|head -n 20 |tail -n 10 >> test.txt

结论:
灵活运用管道符 | ,管道符用于连接多个命令,前一个命令的结果作为下一个命令的输入参数。简单来说,grep前面的筛选结果在后面再筛选几次,然后head,把所输出的内容的前几行输出。
有用的话,点个赞呗~
有问题欢迎留言????

相关标签: 笔记