57

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

97

You just need to negate the match using !:

sed -i '/^##Input/! s/foo/bar/g' myfile
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • 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,817
  • 2
  • 25
  • 25
-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 \{
Keith Tyler
  • 719
  • 4
  • 18
  • 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 Oct 18 '22 at 09:25