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

linux系统上使用sed命令进行文件内字符串替换是非常顺畅的。例如,以下命令在linux上可以无缝工作:

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

然而,在macos上使用相同的命令时,可能会遇到错误。这是因为macos和Linux在处理sed命令的-i选项上存在差异。具体来说,macOS使用的是BSD版本的sed,而Linux使用的是gnu版本的sed。

根据Stack overflow上的一篇帖子《sed command with -i option (in-place editing) works fine on ubuntu but not Mac》,我们了解到-i选项在两者之间处理方式的细微差别。在macOS上,-i选项需要一个后缀参数,即使你不希望创建备份文件,也必须提供一个空字符串作为后缀。例如:

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

Linux版本的sed允许-i选项后跟一个可选的后缀,如果不提供后缀,则不会创建备份文件:

       -i[SUFFIX], --in-place[=SUFFIX]              edit files in place (makes backup if SUFFIX supplied)

而在macOS上,-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和macOS上都能正确使用sed -i选项,可以采用以下方法进行调整:

# 定义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的语法,可以考虑在macOS上安装gsed:

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

参考资料《sed command with -i option (in-place editing) works fine on Ubuntu but not Mac [duplicate]》

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享