How to replace the nth occurrence of a string using sed

后端 未结 1 1678
心在旅途
心在旅途 2020-11-28 12:59

Is there any way to replace the nth occurrence of a string in a file using sed?

I\'m using sed -i \'0,/jack.*/ s//jill/\' to replace the first occurren

相关标签:
1条回答
  • 2020-11-28 13:10

    First replace all the newlines with a unique character that does not occur anywhere else in your file (e.g. ^) using tr. You need to do this in order to create a single string for sed. Then pass it to sed and tell it to replace the nth occurrence of your string. Finally, pass the output back through tr to recreate the newlines.

    For n=2, the command is:

    $ tr '\n' '^' < file | sed 's/jack/jill/2' | tr '^' '\n'
    first line
    second line
    third line
    jack
    fifth line
    jill
    seventh line
    

    Update:

    It can also be done with sed, WITHOUT changing the newlines first, using the following command:

    $ sed ':a;N;$!ba;s/jack/jill/2' file
    

    Alternatively, use awk:

    $ awk '/jack/{c+=1}{if(c==2){sub("jack","jill",$0)};print}' file
    
    0 讨论(0)
提交回复
热议问题