首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >grep -如果一行中包含一个单词而不是另一个字,则打印下10行。

grep -如果一行中包含一个单词而不是另一个字,则打印下10行。
EN

Stack Overflow用户
提问于 2014-08-01 08:11:01
回答 4查看 751关注 0票数 0

我有一个包含行的文件,如下所示:

代码语言:javascript
运行
复制
some strings here class="batch2010" some more strings here click-here
<about 20-30lines here>
some strings here class="batch2006" some more strings here click-here
<about 20-30lines here>
some strings here class="NA" some more strings here click-here
<about 20-30lines here>
some strings here class="batch2010" some more strings here access-denied
<about 20-30lines here>

我想打印包含以下内容的行:

class="batch2010"

但不是:

access-denied

在同一行中,然后在文件中打印下10行。

除了编写一个非常长而复杂的shell脚本之外,还有其他方法吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-08-01 08:14:52

这可以是一个解决方案:

代码语言:javascript
运行
复制
awk 'lines>0 {print; --lines}
     /ass="batch2010"/ && !/access-denied/ {lines=10}' file

请参见输出(不太相关,因为行不多):

代码语言:javascript
运行
复制
$ awk '(lines>0) {print; --lines} /ass="batch2010"/ && !/access-denied/ {lines=10}' a
some strings here class="batch2006" some more strings here click-here
some strings here class="NA" some more strings here click-here
some strings here class="batch2010" some more strings here access-denied

它的逻辑基于How to print 5 consecutive lines after a pattern in file using awk,添加了我们匹配ass="batch2010"和“不匹配”access-denied的部分。

测试

代码语言:javascript
运行
复制
$ seq 30 > a
$ awk 'lines>0 {print; --lines} /4/ && !/14/ {lines=10}' a
5
6
7
8
9
10
11
12
13
14
25
26
27
28
29
30
票数 2
EN

Stack Overflow用户

发布于 2014-08-01 08:13:56

你可以试试

代码语言:javascript
运行
复制
< thefile grep -v 'access-denied' | grep -A10 'class="batch2010"'
票数 2
EN

Stack Overflow用户

发布于 2014-08-01 09:44:10

这可能适用于yoyu (GNU sed):

代码语言:javascript
运行
复制
sed -n '/access-denied/b;/class="batch2010"/{:a;$!{N;s/\n/&/10;Ta};p}' file

如果行包含access-denied,则抛出,否则,如果行包含class="batch2010",请在接下来的10行中读取并打印出来。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25075700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档