Sed replace pattern with line number

后端 未结 7 2271
南方客
南方客 2021-01-05 03:53

I need to replace the pattern ### with the current line number.

I managed to Print in the next line with both AWK and SED.

sed -n \"/###/{

7条回答
  •  一个人的身影
    2021-01-05 04:42

    Given the limitations of the = command, I think it's easier to divide the job in two (actually, three) parts. With GNU sed you can do:

    $ sed -n '/###/=' test > lineno
    

    and then something like

    $ sed -e '/###/R lineno' test | sed '/###/{:r;N;s/###\([^\n]*\n\)\([^\n]*\)/\2\1/;tr;:c;s/\n\n/\n/;tc}'
    

    I'm afraid there's no simple way with sed because, as well as the = command, the r and GNU extension R commands don't read files into the pattern space, but rather directly append the lines to the output, so the contents of the file cannot be modified in any way. Hence piping to another sed command.

    If the contents of test are

    fooo
    bar ### aa
    test
    zz ### bar
    

    the above will produce

    fooo
    bar 2 aa
    test
    zz 4 bar
    

提交回复
热议问题