SED在OSX中使用时添加e后缀文件?

SED adding e suffixed file when used in OSX?

不确定发生了什么,我用 gnu sed 替换了,但我正在以某种方式获取备份文件。这正是我正在做的

mkdir tmp && cd $_
echo 'test' > test.txt
ls
  test.txt

sed -ie 's/test/replaced/g' test.txt
ls
  test.txt
  test.txte

这是怎么回事,我该如何预防?它应该就地编辑,而不是创建备份

sed 版本(GNU sed) 4.2.2

一如既往,man 页面帮助:

-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 edit ing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

您使用 -iee 添加到末尾。删除那个。

根据 mklement0 的精彩评论,POSIX 规范告诉我们:

With optional option-arguments, POSIX utility conventions require that (emphasis his) "a conforming application shall place any option-argument for that option directly adjacent to the option in the same argument string, without intervening characters.

由于 GNU sed 认为 -i 的后缀参数是可选的,因此要求它与选项参数相对应,因此当您编写 -ie GNU sed 将其解释为请求后缀e 用于 -i 参数。 (出于底部附加​​信息中解释的原因,BSD sed 会以相同的方式解释它。)

这意味着您需要使用 -i -e 来获得您想要的行为(对于 GNU sed)(对于 BSD sed,您需要 -i '' -e)。


有关 GNU sed 和 BSD sed 之间不幸但有趣的区别的其他详细信息:

GNU sed 和 BSD sed (OSX sed) 对 -i 参数的后缀值是可选的还是强制的存在分歧。

这很重要,因为作为对上述 POSIX 要求的补充,我们在规范中也发现了以下内容(再次强调 mkelement0's):

an option with a mandatory option-argument [...], a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.

GNU sed 认为后缀是可选的(这会导致上述行为),因为它接受拥抱的 e 作为可选参数,但忽略分隔的 -e (或其他任何内容)作为一个单独的参数。

BSD sed 认为后缀是强制性的(即使它可能为空),这意味着该选项应该与带有 space 的标志分开(例如 -i .bak-i '') 尽管如 "However" 注释所示,BSD sed 还允许任何非空后缀与 -i 标志相对应。

正如 mklement0 指出的那样,这种分歧时不时地出现在 SO 上,这意味着您不能以可移植到 GNU 和 BSD 版本的 sed 的方式使用空的就地编辑后缀。