3

I am trying to replace an extended regular expression using sed on macOS 10.14.3 (18D109). If I do not use the extended regular expression then the inline flag works otherwise it does not update the file, however without the -i flag it prints the correct result to the console. Why does it happen, How could I fix it?

$ echo "foo" > foo.txt
$ sed -i -E 's/fo{1,}/123123/g' ./foo.txt

Nothing happens.

$ sed -E 's/fo{1,}/123123/g' ./foo.txt
123123
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Lajos
  • 145

1 Answers1

2

When using sed to edit a document in-place (with a sed implementation that supports this), there will not be any output in the console. The file will instead be transformed in accordance with the editing script.

$ echo "foo" >foo.txt
$ sed -i -E 's/fo{1,}/123123/g' ./foo.txt
$ cat foo.txt
123123

On FreeBSD and macOS, the -i flag of the provided sed implementation has different semantics from what it has with GNU sed, and your command would have created a file called foo.txt-E as a backup of the original file (and the -E option does therefore not take the intended effect). To use -i with no backup suffix, do this:

sed -i '' -E ...

Example on FreeBSD/macOS:

$ echo "foo" >foo.txt
$ sed -i '' -E 's/fo{1,}/123123/g' ./foo.txt
$ cat foo.txt
123123

Related:

Kusalananda
  • 333,661