为什么“sed -n -i”会删除现有文件内容?

2024-04-15

运行 Fedora 25 服务器版本。sed --version给我sed (GNU sed) 4.2.2以及通常的版权和联系信息。我创建了一个文本文件sudo vi ./potential_sed_bug。 Vi 显示该文件的内容(带有:set list启用)为:

don't$
delete$
me$
please$

然后我运行以下命令:

sudo sed -n -i.bak /please/a\testing ./potential_sed_bug

在我们讨论结果之前;这就是sed 手册页 https://linux.die.net/man/1/sed says:

-n,--安静,--沉默 抑制图案空间的自动打印

and

-i[后缀], --in-place[=后缀] 就地编辑文件(如果提供扩展名,则进行备份)。默认操作模式是断开符号链接和硬链接。这可以通过 --follow-symlinks 和 --copy 进行更改。

我也看过其他 sed 命令参考 http://www.grymoire.com/Unix/Sed.html学习如何使用 sed 进行追加。根据我对我所做的研究的理解;生成的文件内容应该是:

don't
delete
me
please
testing

然而,运行sudo cat ./potential_sed_bug给我以下输出:

testing

鉴于这种差异,我对运行的命令的理解是否不正确,或者 sed/环境是否存在错误?


tl;dr

  • 不要使用-n with -i:除非你在你的程序中使用明确的输出命令sed脚本,则不会将任何内容写入您的文件。

  • Using -i产生nostdout(终端)输出,因此您无需执行任何额外操作即可使命令安静。


默认情况下,sed自动将(可能已修改的)输入行打印到其输出目标,无论是隐含的还是显式指定的:默认情况下,打印到stdout(终端,除非重定向);和-i, to a 临时文件最终替换输入文件。

In both cases, -n 抑制这种自动打印,因此 - 除非您使用显式输出函数,例如p或者,就你而言,a - nothing打印到标准输出/写入临时文件。

  • 请注意,自动打印适用于所谓的模式空间,这就是(可能修改过的)input举行;显式输出函数,例如p, a, i and c do not打印到模式空间(用于潜在的后续修改),它们打印直接到目标流/文件, 这就是为什么a\testing尽管使用了-n.

请注意,与-i, sed的隐式打印/显式输出命令only打印到临时文件,而不是打印到标准输出,因此使用命令-i对于标准输出(终端)输出来说总是安静的 - 您不需要做任何额外的事情。


举一个具体的例子(GNU sed句法)。

Since the use of -i is incidental to the question, I've omitted it for simplicity. Note that -i prints to a temporary file first, which, on completion, replaces the original. This comes with pitfalls, notably the potential destruction of symlinks; see the lower half of this answer https://stackoverflow.com/a/30066428/45375 of mine.

# Print input (by default), and append literal 'testing' after 
# lines that contain 'please'.
$ sed '/please/ a testing' <<<$'yes\nplease\nmore'
yes
please
testing
more

# Adding `-n` suppresses the default printing, so only `testing` is printed.
# Note that the sequence of processing is exactly the same as without `-n`:
# If and when a line with 'please' is found, 'testing' is appended *at that time*.
$ sed -n '/please/ a testing' <<<$'yes\nplease\nmore'
testing

# Adding an unconditional `p` (print) call undoes the effect of `-n`.
$ sed -n 'p; /please/ a testing' <<<$'yes\nplease\nmore'
yes
please
testing
more
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么“sed -n -i”会删除现有文件内容? 的相关文章

随机推荐