【问题标题】:append a line after pattern match ONLY after first occurrence仅在第一次出现后在模式匹配后追加一行
【发布时间】:2015-08-23 00:56:52
【问题描述】:

我有多个文件,如下所示

module ( 
input a;
output b;
);

xx inst_xx (
.in     (xxin),
.ou     (xxou)
);

assign a = b;

endmodule 

我想在第一次出现); 模式之后添加一行

`include "defines.vh" 

所以最后它应该看起来像

module ( 
input a;
output b;
);
`include "defines.vh"

xx inst_xx (
    .in     (xxin),
    .ou     (xxou)
);

assign a = b;

endmodule 

任何使用sedawk 的东西都会很有用。

【问题讨论】:

  • xx inst_xx开头的块呢?那也应该在输出中吗?
  • 不,需要忽略提到的块xx inst_xx。刚刚更正了所需的输出。

标签: awk sed


【解决方案1】:
$ awk '{ print } !flag && /);/ { print "`include \"defines.vh\""; flag = 1 }' file
module (
input a;
output b;
);
`include "defines.vh"

xx inst_xx (
.in     (xxin),
.ou     (xxou)
);

assign a = b;

endmodule

【讨论】:

    【解决方案2】:

    这可能对你有用(GNU sed):

    sed $'/);/{a`include "defines.vh"\n;:a;n;ba}' file
    

    或:

    sed -e '/);/{a`include "defines.vh"' -e ':a;n;ba}' file
    

    这匹配第一个 ); 并附加所需的字符串,然后读取并打印在 n 命令上循环的文件的其余部分。

    【讨论】:

    • 你能解释一下它的作用吗?
    • 如果你能解释每封信,我会很好。谢谢
    猜你喜欢
    • 2013-09-30
    • 2015-04-29
    • 2013-11-25
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2017-02-22
    相关资源
    最近更新 更多