给定输入:
Via: 1.1.1.1
not relevant line
keyword + some text
...
not relevant line N
keyword + some text
...
not relevant line N
Via: 2.2.2.2
not relevant line
keyword + some text
...
not relevant line N
keyword + some text
...
not relevant line N
Via: 3.3.3.3
not relevant lines
Via: 4.4.4.4
not relevant
Via: 5.5.5.5
not relevant line
keyword + some text
...
not relevant line N
keyword + some text
...
not relevant line N
not relevant line N
...
所需输出:
Via: 1.1.1.1
keyword + some text A
keyword + some text A
Via: 2.2.2.2
keyword + some text B
keyword + some text C
Via: 5.5.5.5
keyword + some text D
keyword + some text E
关键字字符串可以在任何 Via 块中出现 N 次,也可以根本不出现。在输出中,我只需要那些关键字与属于它们的关键字字符串一起出现的 Via 块。我找到的最接近的答案是这里,但我无法将其变成我所需要的。
答案1
和sed
:
sed -n '/^Via:/{ x; /keyword/p; d; }; /keyword/H; ${ x; /keyword/p; }' input.txt
或者,如果您想keyword
锚定在行首:
sed -n '/^Via:/{ x; /\nkeyword/p; d; }; /^keyword/H; ${ x; /\nkeyword/p; }' input.txt
答案2
awk解决方案:
awk '/^Via:/{ f=1; r=$0; kw=0; next }
f && /keyword/{ printf "%s%s\n",(!kw)? r ORS:"",$0; kw++ }' file
/^Via:/
- 捕获以变量开头Via:
的行r
。将标志设置f=1
为“活动”状态,指示某个Via
块的处理kw
- 表示数量的标志“关键词”Via
每个块下的线f && /keyword/
- 处理块下的行时Via
- 仅考虑与keyword
模式匹配的行
答案3
简单易行:
cat input.txt | grep "Via:\|keyword" | grep -B1 "keyword"