【问题标题】:Awk insert text from a file before 2 specific linesawk 在 2 个特定行之前从文件中插入文本
【发布时间】:2015-03-27 21:18:22
【问题描述】:

我有 2 个文件,file1 和 file2。

# cat /tmp/file1
***** insert new text ****

# cat /tmp/file2

</table>
some text
</table>
<table name="test" description="test line">
some text

我想将 file1 中的文本插入到 file2 中,但只能在以下 2 行之前:

</table>
<table name="test" description="test line">

所以最终结果是:

</table>
some text
*** insert new text ****
</table>
<table name="test" description="test line">
some text

这是我正在尝试的 awk 语句/命令,但问题是 awk 正在为每个匹配项插入新文本。

# f1="$(</tmp/file1)"
# awk -vf1="$f1" '/<\/table>/,/<table name="test" description="test line">/{print f1;print;next}1' /tmp/file2

***** insert new text ****
</table>
***** insert new text ****
some text
***** insert new text ****
</table>
***** insert new text ****
<table name="test" description="test line">
some text

如何修复 awk 语句以仅在特定的 2 行之前插入来自 file1 的文本?提前致谢。

【问题讨论】:

    标签: awk


    【解决方案1】:

    这对我有用:

    awk '{if(p=="</table>"&&$0=="<table name=\"test\" description=\"test line\">")
    {system("cat file1");}if(p){print p}; p=$0}END{print $0}' file2
    

    if 语句检查当前行是否匹配&lt;table...&gt; 和上一行&lt;/table&gt;。如果是,则打印file1 的内容,否则打印file2 中的行。

    【讨论】:

    • 我认为这也是要走的路,毫无疑问@EdMorton 会有一些巧妙的方法让我们惊叹......
    • 这几乎可以工作,但我错过了输出中包含“description= test line”的行。
    • @user117974 出现错误,我已更改答案,请重试。
    猜你喜欢
    • 2021-02-19
    • 2017-02-25
    • 2015-11-07
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多