1

I'm trying to run a command on macos terminal. The command is to create a .txt file put a string inside of it and then replace a word inside of the .txt file.

I keep getting the error: sed: bad flag in substitute command: '}'

The commands

echo "This is a test file" > test2.txt
sed '/test/{s/test/test2/g}' test2.txt

I also tried:

echo "This is a test file" > test2.txt
sed '/test/\\{s#test#test2#g\\}' test2.txt

But the error here was: sed: 1: "/test/\\{s#test#test2#g\\}": invalid command code \ My assumption is I need to escape the characters but I'm unsure how.

Inian
  • 80,270
  • 14
  • 142
  • 161
Robin
  • 704
  • 8
  • 24

1 Answers1

3

Commands ends with a newline or with ;.

sed '/test/{s/test/test2/g;}'

or

sed '/test/{s/test/test2/g
}'

but just:

sed '/test/s/test/test2/g'

Fun fact: empty regex repeats last regex, so you can just:

sed '/test/s//test2/g'

or really the address is not needed, just:

sed 's/test/test2/g'
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • When this done, I'd also like to save the result back into the test2.txt file, I tried using `sed -i 's/test/test2/g' test2.txt` but it produces an odd error; `sed: 1: "test2.txt": undefined label 'est2.txt'`. – Robin Jan 04 '23 at 09:44
  • 1
    https://stackoverflow.com/questions/12696125/sed-edit-file-in-place note the "when on macos" – KamilCuk Jan 04 '23 at 10:24