假设我们有一个包含以下内容的文件:

chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num
chapter 2 blah blah

我们想把这个文件重新整理一下
chapter 1 blah blahblah num
(下一章前面的一行)。
我们只知道
声明字符串chapter 1 blah blah
在那之后的某处有另一行以chapter开头
一个愚蠢的方法是
grep -A <num> -i "chapter 1" <file>

有足够大的<num>所以整章都在里面。

最佳答案

这很容易用awk

awk '/chapter/ {f=0} /chapter 1/ {f=1} f' file
chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num

如果flagf为true,它将打印行。
chapter 1和nextchapter更改标志。
你可以使用带有awk的范围,但是如果你还有其他的东西要测试的话,它就不那么灵活了。
awk '/chapter 1/,/chapter [^1]/ {if (!/chapter [^1]/) print}' file
chapter 1 blah blah
blah num blah num
num blah num blah
...
blah num

关于linux - grep -A <num>直到一个字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29180929/

10-14 16:25