Search code examples
linuxmacossedbsd

sed in-place flag that works both on Mac (BSD) and Linux


Is there an invocation of sed todo in-place editing without backups that works both on Linux and Mac? While the BSD sed shipped with OS X seems to need sed -i '' …, the GNU sed Linux distributions usually come with interprets the quotes as empty input file name (instead of the backup extension), and needs sed -i … instead.

Is there any command line syntax which works with both flavors, so I can use the same script on both systems?


Solution

  • If you really want to just use sed -i the 'easy' way, the following DOES work on both GNU and BSD/Mac sed:

    sed -i.bak 's/foo/bar/' filename
    

    Note the lack of space and the dot.

    Proof:

    # GNU sed
    % sed --version | head -1
    GNU sed version 4.2.1
    % echo 'foo' > file
    % sed -i.bak 's/foo/bar/' ./file
    % ls
    file  file.bak
    % cat ./file
    bar
    
    # BSD sed
    % sed --version 2>&1 | head -1
    sed: illegal option -- -
    % echo 'foo' > file
    % sed -i.bak 's/foo/bar/' ./file
    % ls
    file  file.bak
    % cat ./file
    bar
    

    Obviously you could then just delete the .bak files.