【问题标题】:What is the function of '-n option' in sed?sed中'-n选项'的作用是什么?
【发布时间】:2014-11-01 06:07:06
【问题描述】:

谁能给我一个例子来展示 -n 选项的用法?文件解释的方式对我来说太模糊了。谢谢

【问题讨论】:

  • 您尝试使用它时发生了什么?

标签: sed option


【解决方案1】:

切换是否打印该行,即使没有匹配。

鉴于这些行:

$ printf '%s\n' {a..c}{0..1} 
a0
a1
b0
b1
c0
c1

-n 只打印匹配“1”的行:

$ printf '%s\n' {a..c}{0..1} | sed -n '/1/p;'
a1
b1
c1

没有-n,每一行都会被打印出来,因为p 命令,匹配“1”的行会被第二次打印出来:

$ printf '%s\n' {a..c}{0..1} | sed  '/1/p;'
a0
a1
a1
b0
b1
b1
c0
c1
c1

通过man sed 轻松获取:

 -n      By default, each line of input is echoed to the standard output
         after all of the commands have been applied to it.  The -n option
         suppresses this behavior.

【讨论】:

    【解决方案2】:

    当您使用sed 作为过滤器并且主要消除材料时,您使用-n 选项,因此您不希望默认打印输入行。在没有-n 的情况下,在每个编辑周期结束时,默认打印模式空间中的“行”。例如:

    sed -n -e '/something/ s/another-thing/dohicky/p' some-file
    

    这会查找包含“某物”的行,并有效地忽略所有其他行。在匹配 'something' 的行上,字符串 'another-thing' 被替换为 'dohicky' 并打印出结果行。

    一个稍微现实一点的例子:把csh的用户shell改成tcsh

    sed -n -e '/\bin\csh/ s%/bin/csh%/bin/tcsh%p' /etc/passwd
    

    这只会向您显示将要更改的行。然后,如果你认为它是正确的,你可以使用:

    sed -i .bak -e '/\bin\csh/ s%/bin/csh%/bin/tcsh%' /etc/passwd
    

    使更改永久化。仍然不是一个很好的例子(您需要锁定密码文件,以便在您编辑它时它不会被其他程序修改等等),但它看起来更真实。

    【讨论】:

      猜你喜欢
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多