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

后端 未结 13 2353
心在旅途
心在旅途 2020-11-22 08:18

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

13条回答
  •  梦谈多话
    2020-11-22 08:44

    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.

提交回复
热议问题