在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便携式命令行。
1条答案
按热度按时间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.
As you discovered, details of the
c
command are also poorly standardized. I would simply suggestwhere 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 ther
andw
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.