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

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

    Here's another version that works on Linux and macOS without using eval and without having to delete backup files. It uses Bash arrays for storing the sed parameters, which is cleaner than using eval:

    # Default case for Linux sed, just use "-i"
    sedi=(-i)
    case "$(uname)" in
      # For macOS, use two parameters
      Darwin*) sedi=(-i "")
    esac
    
    # Expand the parameters in the actual call to "sed"
    sed "${sedi[@]}" -e 's/foo/bar/' target.file
    

    This does not create a backup file, neither a file with appended quotes.

提交回复
热议问题