sed中"-n"的含义究竟是什么?

Jon*_*kel 8 regex unix space sed

根据http://linux.about.com/od/commands/l/blcmdl1_sed.htm

抑制图案空间的自动打印

我有或没有测试过-n,sed会产生相同的结果

我不明白这意味着什么空间.

bra*_*zzi 24

Sed有两个存储文本的地方:模式空间和保留空间.模式空间是每个行由sed命令处理的地方; 保持空间是一个辅助的地方,可以放置一些您可能想要稍后使用的文本.您可能只使用模式空间.

在sed进行处理之前,它被放入模式空间.然后,sed将所有命令(例如s///)应用于de pattern space,默认情况下,从模式空间打印结果文本.让我们假设我们有一个myfile包含以下行的文件:

The quick brown fox jumps over the lazy dog.
Run Code Online (Sandbox Code Playgroud)

我们运行以下命令:

sed 's/fox/coati/;s/dog/dingo/' myfile
Run Code Online (Sandbox Code Playgroud)

桑达将申请s/fox/coati/,然后s/dog/dingo/在文件的每一行-在这种情况下,唯一的一个我们在上面显示.当它发生时,它会将该行放在模式空间中,该空间将具有以下内容:

The quick brown fox jumps over the lazy dog.
Run Code Online (Sandbox Code Playgroud)

然后,sed将运行第一个命令.sed运行命令后s/fox/coati/,模式空间的内容将是:

The quick brown coati jumps over the lazy dog.
Run Code Online (Sandbox Code Playgroud)

然后sed将应用第二个命令,即s/dog/dingo/.之后,模式空间的内容将是:

The quick brown coati jumps over the lazy dingo.
Run Code Online (Sandbox Code Playgroud)

请注意,这只发生在内存中 - 现在没有打印.

在将所有命令应用于当前行之后,默认情况下,sed将获取模式空间的内容并将其打印到标准输出.但是,当您-n作为sed的选项提供时,您要求sed不执行此最后一步,除非明确要求.所以,如果你跑

sed -n 's/fox/coati/;s/dog/dingo/' myfile
Run Code Online (Sandbox Code Playgroud)

什么都不打印.

但你怎么能明确要求sed打印模式空间?好吧,你可以使用p命令.当sed找到此命令时,它将立即打印模式空间的内容.例如,在下面的命令中,我们请求sed在第一个命令之后打印模式空间的内容:

sed -n 's/fox/coat/;p;s/dog/dingo/' myfile
Run Code Online (Sandbox Code Playgroud)

结果将是

$ sed -n 's/fox/coati/;p;s/dog/dingo/' myfile 
The quick brown coati jumps over the lazy dog.
Run Code Online (Sandbox Code Playgroud)

请注意,仅fox替换.发生这种情况是因为在打印模式空间之前未执行第二个命令.如果我们想在两个命令之后打印模式空间,我们只需要放在p第二个命令之后:

sed -n 's/fox/coati/;s/dog/dingo/;p' myfile
Run Code Online (Sandbox Code Playgroud)

如果您使用该s///命令,另一个选项是将p标志传递给s///:

sed -n 's/fox/coati/;s/dog/dingo/p' myfile 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,只有在执行了标记的替换时才会打印该行.它可能非常有用!


anu*_*ava 9

试试sed什么都不做:

sed '' file
Run Code Online (Sandbox Code Playgroud)

sed -n '' file
Run Code Online (Sandbox Code Playgroud)

首先打印整个文件,但第二个不打印任何东西.

  • @VictoriaStuart我只是浪费了2个小时的生命来尝试调试sed,同时传递`-n`和`-i`.我有一个空文件,但没有得到原因.我刚刚停下来,因为我看到了你的评论,谢谢! (3认同)
  • 另外:如果你使用-i( - in-place:编辑到位;静默编辑),不要将它与-n {-in |结合使用 -ni | -i -n | -n -i},因为你会得到意想不到的结果,包括空(0字节)输出文件. (2认同)

Lee*_*ton 7

这会将 sed 置于安静模式,其中 sed 将抑制所有输出,除非命令明确指定p

   -n 
   --quiet 
   --silent
          By default, sed will print out the pattern space at
          the  end  of  each cycle through the script.  These
          options disable this automatic  printing,  and  sed
          will  only  produce  output when explicitly told to
          via the p command.
Run Code Online (Sandbox Code Playgroud)

例如,如果您想使用 sed 来模拟 grep 的操作:

$echo -e "a\nb\nc" | sed -n '/[ab]/ p'
a
b
Run Code Online (Sandbox Code Playgroud)

如果没有,-n您将得到 c 的出现(以及 a 和 b 的两次出现)