Reputation: 59
File is like :
#comment1
some executable code
#comment2
some executable code
I want to insert two hashes before 2nd and 4th line, so I tried, sed 's/^[^#]/##/g' but that replaces the first character ('s' in 2nd line), like :
#comment1
##ome executable code
#comment2
##ome executable code
But I want to get the output like :
#comment1
##some executable code
#comment2
##some executable code
Please suggest some way to do this.
Upvotes: 0
Views: 961
Reputation: 754030
Use sed 's/^[^#]/##&/'
.
The &
in the replacement part means 'what was matched'.
There's no need for a g
when the search is anchored at the start of the line; it can only match once on a given line. OTOH, it doesn't actually do any damage.
I note that for the input file:
#comment1
some executable code
#comment2
some executable code
your original output would have been:
#comment1
##some executable code
#comment2
##some executable code
because the leading space would have been lost. With the revised script, the output would preserve the leading space:
#comment1
## some executable code
#comment2
## some executable code
Upvotes: 1
Reputation: 785256
Since [^#]
is matching a character you need to place it back in replacement:
sed 's/^[[:blank:]]*\([^#]\)/##\1/' file
#comment1
##some executable code
#comment2
##some executable code
^[[:blank:]]*
matches 0 or spaces/tabs at start.
Upvotes: 0