sed -i command for in-place editing to work with both GNU sed and BSD/OSX

后端 未结 7 1144
攒了一身酷
攒了一身酷 2020-11-28 04:09

I\'ve got a makefile (developed for gmake on Linux) that I\'m attempting to port to MacOS, but it seems like sed doesn\'t want to cooperate. What I

7条回答
  •  天命终不由人
    2020-11-28 04:29

    The currently accepted answer is flawed in two very important ways.

    1. With BSD sed (the OSX version), the -e option is interpreted as a file extension and therefore creates a backup file with a -e extension.

    2. Testing for the darwin kernel as suggested is not a reliable approach to a cross platform solution since GNU or BSD sed could be present on any number of systems.

    A much more reliable test would be to simply test for the --version option which is only found in the GNU version of sed.

    sed --version >/dev/null 2>&1
    

    Once the correct version of sed is determined, we can then execute the command in its proper syntax.

    GNU sed syntax for -i option:

    sed -i -- "$@"
    

    BSD sed syntax for -i option:

    sed -i "" "$@"
    

    Finally put it all together in a cross platform function to execute an in place edit sed commend:

    sedi () {
        sed --version >/dev/null 2>&1 && sed -i -- "$@" || sed -i "" "$@"
    }
    

    Example usage:

    sedi 's/old/new/g' 'some_file.txt'
    

    This solution has been tested on OSX, Ubuntu, Freebsd, Cygwin, CentOS, Red Hat Enterprise, & Msys.

提交回复
热议问题