60

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!

3 Answers 3

101

You just need to negate the match using !:

sed -i '/^##Input/! s/foo/bar/g' myfile
2
  • 4
    This is so useful! I didn't realize you could give sed an input that matches the line before you run the search and replace on that line. This helps me immensely! Commented Jun 7, 2018 at 21:56
  • 1
    @bballdave025: See the addresses section of the GNU sed manual to learn more. Commented Jun 8, 2018 at 4:07
-5

You got to escape # as in \#.

1
  • 5
    There's no need to escape the #. It has no special meaning to sed. Commented Feb 10, 2011 at 5:49
-10

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 \{
1
  • I fail to see how it's an 'ugly request' but your comment might be called that. Also it doesn't really answer the question. I mean okay it might be understandable what that means but to someone asking the question do you really think they'll understand that sed invocation? And who said anything about a json file anyway ?
    – Pryftan
    Commented Oct 18, 2022 at 9:25