macOS:sed -i报错:sed: 1: “xxxxx“: extra characters at the end of p command

如下,执行sed对文件中的字符串进行替换,在Linux下是一点问题没有的。

sed -i "s/find/replace/g" file.txt

但是在macOS下却报错了

sed: 1: “file.txt”: extra characters at the end of p command

在stackoverflow上找到这个帖子《sed command with -i option (in-place editing) works fine on Ubuntu but not Mac》1,总算知道了原因:macOS与linux还是有差异的,这个问题就是macOS与linux之间差异造成的。

简言之,就是BSD/macOS 的sed和linux(GNU)下的sed 对于-i参数的处理有微小的差异。

-i 即inplace,即对文件原地修改,-i 后面可以指定一个后缀,比如(mscOS) -i .bak,或在linux下 -i.bak 即修改原文件并保存一个后缀为.bak的修改前的备份

如下是Linux下sed -i 参数说明

       -i[SUFFIX], --in-place[=SUFFIX]

              edit files in place (makes backup if SUFFIX supplied)

如下是macOS下sed -i 参数说明

     -I extension
             Edit files in-place, saving backups with the specified extension.
             If a zero-length extension is given, no backup will be saved.  It
             is not recommended to give a zero-length extension when in-place
             editing files, as you risk corruption or partial content in situ-
             ations where disk space is exhausted, etc.

             Note that in-place editing with -I still takes place in a single
             continuous line address space covering all files, although each
             file preserves its individuality instead of forming one output
             stream.  The line counter is never reset between files, address
             ranges can span file boundaries, and the ``$'' address matches
             only the last line of the last file.  (See Sed Addresses.)  That
             can lead to unexpected results in many cases of in-place editing,
             where using -i is desired.

     -i extension
             Edit files in-place similarly to -I, but treat each file indepen-
             dently from other files.  In particular, line numbers in each
             file start at 1, the ``$'' address matches the last line of the
             current file, and address ranges are limited to the current file.
             (See Sed Addresses.)  The net result is as though each file were
             edited by a separate sed instance.

上面的说明可以看出区别Linux下-i 参数后面的[SUFFIX]是可选的(且与-i之间没有空格),如果不指定就不会备份
而macOS下-i参数后面的extension(扩展名,后缀)是必填参数(且与-i之间要有空格隔开),如果不想指定备份文件怎么办?必须跟一个空字符串,也就是-i ""
所以回到前面的那个例子,在macOS下就应该这么写

sed -i "" "s/find/replace/g" file.txt

如果你的脚本中很多地方都要用到sed -i 原地修改,而又希望在Linux和macOS下都能正常使用,推荐如下方式做一个替换:

# 定义sed -i 参数(数组)
# Default case for Linux sed, just use "-i"
sedi=(-i)
case "$(uname)" in
  # For macOS, use two parameters
  Darwin*) sedi=(-i "")
esac	

########

sed "${sedi[@]}" "s/find/replace/g" file.txt

如果你还是希望使用GNU sed 语法,可以参考下面的解决办法安装gsed
在这里插入图片描述

参考资料


  1. 《sed command with -i option (in-place editing) works fine on Ubuntu but not Mac [duplicate]》 ↩︎

Guess you like

Origin blog.csdn.net/10km/article/details/121715946