Sed replace pattern with line number

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

    This might work for you (GNU sed):

    sed = file | sed 'N;:a;s/\(\(.*\)\n.*\)###/\1\2/;ta;s/.*\n//'
    
    0 讨论(0)
  • 2021-01-05 04:36

    Following on from https://stackoverflow.com/a/53519367/29924

    If you try this on osx the version of sed is different and you need to do:

    seq 1 `wc -l FILE | awk '{print $1}'` | xargs --verbose -IX sed -i bak "X s/__line__/X/" FILE
    

    see https://markhneedham.com/blog/2011/01/14/sed-sed-1-invalid-command-code-r-on-mac-os-x/

    0 讨论(0)
  • 2021-01-05 04:39

    Simple awk oneliner:

    awk '{gsub("###",NR,$0);print}'
    
    0 讨论(0)
  • 2021-01-05 04:39

    is this ok ?

    kent$  echo "a
    b
    c
    d
    e"|awk '/d/{$0=$0" "NR}1'
    a
    b
    c
    d 4
    e
    

    if match pattern "d", append line number at the end of the line.

    edit

    oh, you want to replace the pattern not append the line number... take a look the new cmd:

    kent$  echo "a
    b
    c
    d
    e"|awk '/d/{gsub(/d/,NR)}1'
    a
    b
    c
    4
    e
    

    and the line could be written like this as well: awk '1+gsub(/d/,NR)' file

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-05 04:44

    one-liner to modify the FILE in place, replacing LINE with the corresponding line number:

    seq 1 `wc -l FILE | awk '{print $1}'` | xargs -IX sed -i 'X s/LINE/X/' FILE
    
    0 讨论(0)
提交回复
热议问题