使用shell脚本在模式匹配后删除或替换文件中的第n行

时间:2014-12-30 23:34:25

标签: bash shell awk sed

我需要在模式匹配后替换第11行" msq_Query"在文件中,原始文本应保持不变。 单线sed或awk会有所帮助!!

*msq_Query
{
    { BaconOutput1, 0419000000, 0144567891,
        <
        OIN ,
        TIN ,
        BPARTY
        >
    ,
        <
        >
    , 1477361456, 0}
}

在文件的第11行中,number(whihc可以是随机的)应该替换为0 要么 应删除第11行。

2 个答案:

答案 0 :(得分:3)

我认为最简单的方法是使用这样的awk:

awk -v lines=11 'BEGIN { ignore = -1 } /pattern/ { ignore = NR + lines } NR != ignore { print }' filename

用您自己的模式替换pattern

其工作原理如下:

BEGIN { ignore = -1 }             # initialize ignore with -1 so NR will never
                                  # be equal to it by accident

/pattern/ { ignore = NR + lines } # when the pattern is found, set ignore to the
                                  # line we want to ignore

NR != ignore { print }            # unless the current line is that line, print
                                  # it.

为了替换行中的某些内容而不是删除它,脚本可以修改如下:

awk -v lines=11 'BEGIN { mark = -1 } /pattern/ { mark = NR + lines } NR == mark { sub(/[0- 9]+/, "") } { print }' filename

即:

BEGIN { mark = -1 }                # initialize mark with -1 so NR will never
                                   # be equal to it by accident

/pattern/ { mark = NR + lines }    # when the pattern is found, set mark to the
                                   # line we want to ignore

NR == mark { sub(/[0-9]+/, "0"); } # if that line is the current line, substitute
                                   # stuff (stuff can be freely chosen)

{ print }                          # print all the lines.

答案 1 :(得分:0)

我能想到的最简单方法

delete

awk '/pattern/{x=12}x--!=1' file

&#39;替换&#39;

awk '/pattern/{x=12}x--==1{$0="REPLACEMENT"}1' file