55

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 Answers3

91

You just need to negate the match using !:

sed -i '/^##Input/! s/foo/bar/g' myfile
Dennis Williamson
  • 324,833
  • 88
  • 366
  • 429
  • 3
    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! – bballdave025 Jun 07 '18 at 21:56
  • 1
    @bballdave025: See the [addresses](https://www.gnu.org/software/sed/manual/sed.html#sed-addresses) section of the GNU `sed` manual to learn more. – Dennis Williamson Jun 08 '18 at 04:07
-5

You got to escape # as in \#.

vpit3833
  • 7,693
  • 2
  • 24
  • 25
-9

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 \{
Keith Tyler
  • 657
  • 3
  • 16