Search code examples
linuxsed

Copy line with subtitution before the line itself with sed


Here's my input

dummy
This is a line
dummy
dummy
this is another line

the output should be

dummy
# This is a line
This is a line
dummy
dummy
# this is another line
this is another line

Which is quite simple IMO...

Just tried the sed below but this wouldn't add the pattern found. It just prints # above the line.

 sed -i '/^this/I i\ '#' & ' $file  

Thoughts? Thanks.

Seems like this syntax is not the right way to achieve this.


Solution

  • This might work for you (GNU sed):

    sed '/dummy/I!s/.*/# &\n&/' file
    

    If a line does not contain the word dummy, then duplicate the line with the first duplicate prepended with # .