user438602
user438602

Reputation:

How to globally replace strings in lines NOT starting with a certain pattern

I want to globally replace the string foo with the string bar, using sed. This should only be done for lines which do NOT start with the string ##Input.

I can't get it to work. I tried things like this but reached a point where I'm not sure if I know what I'm doing:

sed -i '/^##Input/ s/foo/bar/g' myfile

Please help!

Upvotes: 60

Views: 41995

Answers (3)

Keith Tyler
Keith Tyler

Reputation: 825

An ugly answer for an ugly request (i.e. they get what they asked for):

echo \{
for file in *.json; do
    sed -n '/^[\{\}]/! s/\([^\,]\)$/\1,/; /^[\{\}]/!p' $file
done
echo \{

Upvotes: -10

Dennis Williamson
Dennis Williamson

Reputation: 360445

You just need to negate the match using !:

sed -i '/^##Input/! s/foo/bar/g' myfile

Upvotes: 101

vpit3833
vpit3833

Reputation: 7961

You got to escape # as in \#.

Upvotes: -5

Related Questions