sed: bad flag in substitute command: '}'

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.

>Solution :

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'

Leave a Reply