【问题标题】:accessing text between specific words in UNIX multiple times多次访问 UNIX 中特定单词之间的文本
【发布时间】:2014-03-20 01:02:08
【问题描述】:

如果文件是这样的:

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

现在我想同时访问ram_fileend_filetony_fileend _filebravo_fileend_file 之间的文本。我尝试了sed 命令,但我不知道如何在此指定*_file

提前致谢

【问题讨论】:

    标签: linux shell unix sed


    【解决方案1】:

    这个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
    

    【讨论】:

    • +1;可能更好地锚定 ..._file 正则表达式。
    • +1:为了更好的解决方案,让我们删除我们的答案! :P
    • @jaypal Uff,希望我没有让任何人感到难过,这不是我的本意 :) 理解请求是什么并不总是好的,可能需要一些时间才能完成。
    • @Jotne 一点也不。昨天,有人帮我调试perl script 超过 3 小时。我们将性能从几分钟缩短到 9 秒。让别人调试你的答案是一项艰巨的任务,所以我真的很感激。只有当您尝试解决所有边缘场景时,您才会打开学习之门!干杯,谢谢!继续做好事!!
    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多