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

后端 未结 13 2298
心在旅途
心在旅途 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:39

    If you need to do sed in-place in a bash script, and you do NOT want the in-place to result with .bkp files, and you have a way to detect the os (say, using ostype.sh), -- then the following hack with the bash shell built-in eval should work:

    OSTYPE="$(bash ostype.sh)"
    
    cat > myfile.txt <<"EOF"
    1111
    2222
    EOF
    
    if [ "$OSTYPE" == "osx" ]; then
      ISED='-i ""'
    else # $OSTYPE == linux64
      ISED='-i""'
    fi
    
    eval sed $ISED 's/2222/bbbb/g' myfile.txt
    ls 
    # GNU and OSX: still only myfile.txt there
    
    cat myfile.txt
    # GNU and OSX: both print:
    # 1111
    # bbbb
    
    # NOTE: 
    # if you just use `sed $ISED 's/2222/bbbb/g' myfile.txt` without `eval`,
    # then you will get a backup file with quotations in the file name, 
    # - that is, `myfile.txt""`
    

提交回复
热议问题