Madhura Pande
Madhura Pande

Reputation: 59

sed command to insert a character before another character with a 'not' match

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

Answers (2)

Jonathan Leffler
Jonathan Leffler

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

anubhava
anubhava

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

Related Questions