Skip to main content

% ins3cure.com

Editing files in-place with sed on macOS

Editing files in-place with sed will probably give you an error in macOS if you use the syntax you’re used to in Linux bash.

macOS must be using a differet sed version so this happens when you try to edit files in-place with -i argument:

% sed -i 's/search/replace/g' file.txt
sed: 1: "file.txt": invalid command code f

…or some other errors that apparently depend on the first letter of the file name 😄

  • sed: 1: "file.txt": invalid command code f
  • sed: 1: "homebrew.md": extra characters at the end of h command
  • sed: 1: "a": command a expects \ followed by text

This is because Linux uses the GNU sed version while macos uses the BSD version.

The macOS version requires an extension for the backup files (which can be empty but it is still mandatory) so this is a valid syntax example:

% sed -i'.bak' 's/search/replace/g' file.txt

Of course you can use:

% sed -i'' 's/search/replace/g' file.txt

but do it at your own risk!

comments powered by Disqus