【问题标题】:sed insert multiple lines before multiple lines patternsed 在多行模式之前插入多行
【发布时间】:2018-08-02 22:14:19
【问题描述】:

我有以下很长的文件:

...
close unit 1
...
...
close unit 1
...
...
close unit 1

stop

我想在stop 之前的最后一个close unit 1 之前插入多行。该文件包含未定义数量的close unit 1

我在这里和那里发现了很多其他类似的问题,但答案对我没有帮助......例如我尝试了https://stackoverflow.com/a/8635732/1689664,但这没有用......

【问题讨论】:

    标签: sed pattern-matching


    【解决方案1】:

    使用sedtac

    $ tac inputfile | sed '/close unit 1/ {s/\(.*\)/\1\nLine3\nLine2\nLine1/; :loop; n; b loop}' | tac
    ...
    close unit 1
    ...
    ...
    close unit 1
    ...
    ...
    Line1
    Line2
    Line3
    close unit 1
    
    stop
    

    请注意,您需要在sed 表达式中以相反的顺序指定输入

    【讨论】:

    • 嗯,有时我没有得到任何输出...你有没有遇到过这种情况?
    • @Kyle_the_hacker 你能发布一个不起作用的例子吗?
    • 这会时不时产生0字节的文件:for i in * do tac $i | sed '/关闭单元 1/ {s/(.*)/\1\nLine3\nLine2\nLine1/; :环形; n; b 循环}' |塔克 |发球台$我完成了
    【解决方案2】:

    Perl 解决方案:

    perl -ne '  push @arr, $_;
                print shift @arr if @arr > 3;
                if ("stop\n" eq $_ and "close unit 1\n" eq $arr[0]) {
                    print "\n\n";                                     # Inserted lines
                }
             }{ print @arr ' long-file > new-file
    

    它保留最后3行的滑动窗口,如果窗口中的最后一行是stop,第一行是close unit 1,则打印这些行。

    另一种可能性是使用nl 为行编号,然后使用grep 包含close unit 1 的行,获取最后一行的编号并将其用于sed 地址:

    nl -ba long-file \
        | grep -F 'close unit 1' \
        | tail -n1 \
        | ( read line junk
            sed -e $line's/^/\n\n/' long-file > new-file
          )
    

    【讨论】:

    • 我想避免 perl :/
    • @Kyle_the_hacker:为什么?
    • 因为我不擅长 Perl,所以尽量减少我使用的不同脚本语言的数量。
    【解决方案3】:

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

    sed '/close unit 1/,$!b;/close unit 1/{x;/./p;x;h;d};H;$!d;x;i\line 1\nline 2\n...' file
    

    正常打印close unit 1 第一次出现之前的每一行。在保留空间中存储以close unit 1 开头的行集合,并在存储下一个集合之前打印上一个集合。在文件的末尾,最后一个集合仍然在保留空间中,因此插入所需的行,然后打印最后一个集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 2014-09-07
      相关资源
      最近更新 更多