shell awk打印范围

时间:2014-02-26 11:04:59

标签: bash shell awk

我的txt文件构造如下:

random text
random text
random text

start_here
important text
important text
important text
end_here

random text
random text

start_here
important text
important text
important text
end_here

...
start_here
...
end_here
...

我需要在新文件中打印start_here和end_here之间的所有内容(无论这些行是否存在)。

我尝试使用awk,但输出文件为空。

awk '/start_here/,/end_here/' inputfile.txt > outputfile.txt

我的错误在哪里?

3 个答案:

答案 0 :(得分:1)

这对我来说很好,但你可以尝试:

awk '/start_here/{f=1} f; /end_here/{f=0}' file

awk '/start_here/{f=1} /end_here/{f=0;print} f' file

所有人都给出了这个:

start_here
important text
important text
important text
end_here
start_here
important text
important text
important text
end_here
start_here
...
end_here

如果你不喜欢开头/结尾文本,请使用:

awk '/end_here/{f=0} f; /start_here/{f=1}' file

important text
important text
important text
important text
important text
important text
...

答案 1 :(得分:0)

您的代码应该有效 我测试了here

你也可以使用perl:

perl -lne 'print if(/start_here/.../end_here/)'

经过测试here

答案 2 :(得分:0)

您的脚本几乎是一个有效的sed脚本:

sed -n '/start_here/,/end_here/p' inputfile.txt > outputfile.txt