多次访问UNIX中特定单词之间的文本

时间:2014-03-19 14:42:06

标签: linux shell unix sed

如果文件是这样的:

ram_file
abc
123
end_file
tony_file
xyz
456
end_file
bravo_file
uvw
789
end_file

现在我想访问ram_fileend_file之间的文字,tony_file& end _filebravo_file&同时end_file。我尝试了sed命令,但我不知道如何在此指定*_file

提前致谢

1 个答案:

答案 0 :(得分:2)

这个awk应该为你完成工作。

此解决方案威胁end_file作为块的结尾,并将所有其他xxxx_file作为块的开头。
它不会在块之间打印文本,例如我的示例do not print this

awk '/end_file/{f=0} f; /_file/ && !/end_file/ {f=1}' file
abc
123
xyz
456
uvw
789

cat file
ram_file
abc
123
end_file
do not print this
tony_file
xyz
456
end_file
nor this data
bravo_file
uvw
789
end_file

如果您喜欢某种格式,可以使用awk

轻松完成
awk -F_ '/end_file/{printf (f?RS:"");f=0} f; /file/ && !/end_file/ {f=1;print "-Block-"++c"--> "$1}' file
-Block-1--> ram
abc
123

-Block-2--> tony
xyz
456

-Block-3--> bravo
uvw
789