sed command with -i option failing on Mac, but works on Linux

前端 未结 12 1906
情歌与酒
情歌与酒 2020-11-22 05:04

I\'ve successfully used the following sed command to search/replace text in Linux:

sed -i \'s/old_link/new_link/g\' *

However,

相关标签:
12条回答
  • 2020-11-22 06:02

    Here's how to apply environment variables to template file (no backup need).

    1. Create template with {{FOO}} for later replace.

    echo "Hello {{FOO}}" > foo.conf.tmpl
    

    2. Replace {{FOO}} with FOO variable and output to new foo.conf file

    FOO="world" && sed -e "s/{{FOO}}/$FOO/g" foo.conf.tmpl > foo.conf
    

    Working both macOS 10.12.4 and Ubuntu 14.04.5

    0 讨论(0)
  • 2020-11-22 06:07

    Had the same problem in Mac and solved it with brew:

    brew install gnu-sed
    

    and use as

    gsed SED_COMMAND
    

    you can set as well set sed as alias to gsed (if you want):

    alias sed=gsed
    
    0 讨论(0)
  • 2020-11-22 06:08

    Sinetris' answer is right, but I use this with find command to be more specific about what files I want to change. In general this should work (tested on osx /bin/bash):

    find . -name "*.smth" -exec sed -i '' 's/text1/text2/g' {} \;
    

    In general when using sed without find in complex projects is less efficient.

    0 讨论(0)
  • 2020-11-22 06:09

    I believe on OS X when you use -i an extension for the backup files is required. Try:

    sed -i .bak 's/hello/gbye/g' *
    

    Using GNU sed the extension is optional.

    0 讨论(0)
  • 2020-11-22 06:10

    If you use the -i option you need to provide an extension for your backups.

    If you have:

    File1.txt
    File2.cfg
    

    The command (note the lack of space between -i and '' and the -e to make it work on new versions of Mac and on GNU):

    sed -i'.original' -e 's/old_link/new_link/g' *
    

    Create 2 backup files like:

    File1.txt.original
    File2.cfg.original
    

    There is no portable way to avoid making backup files because it is impossible to find a mix of sed commands that works on all cases:

    • sed -i -e ... - does not work on OS X as it creates -e backups
    • sed -i'' -e ... - does not work on OS X 10.6 but works on 10.9+
    • sed -i '' -e ... - not working on GNU

    Note Given that there isn't a sed command working on all platforms, you can try to use another command to achieve the same result.

    E.g., perl -i -pe's/old_link/new_link/g' *

    0 讨论(0)
  • 2020-11-22 06:10
    sed -ie 's/old_link/new_link/g' *
    

    Works on both BSD & Linux with gnu sed

    0 讨论(0)
提交回复
热议问题