shell 为什么GNU sed在a命令中使用-n选项时会打印输出?

mlnl4t2r  于 2023-08-07  发布在  Shell
关注(0)|答案(2)|浏览(105)

在将sed命令与-n选项和a命令一起使用时,我遇到了一些意外的行为。根据sed手册,-n选项应该在脚本的每个循环结束时抑制模式空间的自动打印。但是,当我运行以下命令:

echo a | sed -n -e ‘$a b’

字符串
它打印b,即使我希望它什么也不打印。
我尝试运行echo a | sed -n -e '$a b'命令,由于-n选项,我希望它什么也不打印。但是,它打印了b,这是出乎意料的。如果这是GNUsed在一起使用这些选项时的预期行为,那就意味着我误解了它们应该如何工作。有人能解释一下为什么会这样吗?

jljoyd4f

jljoyd4f1#

echo a | sed -n -e ‘$a b’

字符串
印刷品

b


和/或

echo a | sed -e ‘$a b’


印刷品

a
b


其示出了当指定-n时,不打印 * 图案空间 * 的内容。

fdx2calv

fdx2calv2#

为了扩展Diego的优秀答案,-n选项基本上说“除非我要求什么否则闭嘴”,但如果它完全抑制了所有输出,它将是无用的,是吗?
基本上,任何时候你 * 告诉 * sed你想要输出,它仍然会给予它。

$: cat file
<this is the content of "file">
$: printf "%s\n" {a..z} | sed -n '
2=           # the line number
3p           # print this line
4l           # "list" unambiguously
5r file
/f/a oo      # add - still hides f
/m/i hi      # insert - still hides m
/q/c silent! # change - new value shows
' # note a i and c include the comment.
2
c
d$
<this is the content of "file">
oo      # add - still hides f
hi      # insert - still hides m
silent! # change - new value shows

字符串
希望能帮上忙。

相关问题