与Linux和MacOs的sed兼容

mspsb9vt  于 2022-12-11  发布在  Linux
关注(0)|答案(1)|浏览(159)

在Linux上,我有一个Bash脚本,其中我使用了sed
不幸的是,在MacOS上,这个版本的sed与Linux sed不一样。
我正在寻找一种在Linux和MacOS上使用兼容sed的方法,即在两个操作系统上使用相同的脚本。
您能否告诉我,在两种操作系统中使用gsed而不是sed是否允许此脚本具有唯一的兼容版本(其中gsed -i在两种操作系统中均适用)

更新1

在我的例子中,在MacOS 10.9.5上,我想用一个变量的值替换文件的line 2。我尝试:

a=2
sed -i'' -e "2c\$a" file.dat

但是该行被"$a"代替,而不是a= 2的值。
接下来我可以尝试什么?
PS:我想得到一个Linux/MacOS便携式命令行。

h79rfbju

h79rfbju1#

There is unfortunately a large number of behaviors in sed which are not adequately standardized. It is hard to articulate a general answer which collects all of these.
For your specific question, a simple function wrapper like this should suffice.

sedi () {
    case $(uname -s) in
        *[Dd]arwin* | *BSD* ) sed -i '' "$@";;
        *) sed -i "$@";;
    esac
}

As you discovered, details of the c command are also poorly standardized. I would simply suggest

sedi "2s/.*/$a/" file.dat

where obviously use a different separator if $a could contain a slash; or if you are using Bash, use ${a//[\/]/\\/} to backslash all slashes in the value.
Other behaviors which differ between implementations include extended regex support ( -r or -E or not available), the ability to pass in multiple script fragments with -e (the portable solution is to separate commands with newlines), the ability to pass standard input as the argument to -f , and the general syntax of several commands (does the filename argument of the r and w commands extend up to the next whitespace, semicolon, or newline? Can you put a command immediately adjacent to a brace? What are the precise semantics of backslashed newlines and where are they mandatory? Where are backslashes before command arguments mandatory?) and obviously regex flags and features.

相关问题