Sed replace pattern with line number

后端 未结 7 2210
南方客
南方客 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:54

    As noted by Lev Levitsky this isn't possible with one invocation of sed, because the line number is sent directly to standard out.

    You could have sed write a sed-script for you, and do the replacement in two passes:

    infile

    a
    b
    c
    d
    e
    ###
    ###
    ###
    a
    b
    ###
    c
    d
    e
    ###
    

    Find the lines that contain the pattern:

    sed -n '/###/=' infile
    

    Output:

    6
    7
    8
    11
    15
    

    Pipe that into a sed-script writing a new sed-script:

    sed 's:.*:&s/###/&/:'
    

    Output:

    6s/###/6/
    7s/###/7/
    8s/###/8/
    11s/###/11/
    15s/###/15/
    

    Execute:

    sed -n '/###/=' infile | sed 's:.*:&s/^/& \&/:' | sed -f - infile
    

    Output:

    a
    b
    c
    d
    e
    6
    7
    8
    a
    b
    11
    c
    d
    e
    15
    
    0 讨论(0)
提交回复
热议问题