【问题标题】:sed replace # with empty linesed 用空行替换 #
【发布时间】:2022-02-16 00:39:29
【问题描述】:

如何使用 sed 将只有 # 的行替换为空行?

我试图在谷歌上找到,但我没有得到任何东西。

文件内容:

#test
another test
#
another test2

预期结果:

#test
another test

another test2

因此,在预期的结果下,经过另一次测试,该行应该是空白的,没有#。

非常感谢任何帮助。

【问题讨论】:

标签: sed


【解决方案1】:

使用正则表达式,您可以用^ 匹配行首,用$ 匹配行尾。 s/regexp/replacement/ 命令会将匹配regexp 的文本替换为replacement

这个sed 命令给出了所需的输出: sed 's/^#$//' < input.txt

在每一行,sed 查找行首、# 字符,然后是行尾,并将其替换为空。但是,换行符仍然存在,因此您只剩下一个空行。

【讨论】:

    【解决方案2】:
    sed '/^#$//'
    
    • 锚定到行的开头 (^) 和结尾 ($) 以精确匹配整行。

    【讨论】:

      【解决方案3】:

      使用sed

      $ sed '/[[:alnum:]]/ ! s/#//' file
      #test
      another test
      
      another test2
      

      【讨论】:

        【解决方案4】:

        这可能对你有用(GNU sed):

        sed '/^#$/g' file
        

        如果一行仅包含#,则将其替换为空行。

        替代方案:

        sed 's/^#$//' file
        

        sed '/^#$/c\\' file
        

        【讨论】:

          猜你喜欢
          • 2014-04-11
          • 1970-01-01
          • 1970-01-01
          • 2018-10-14
          • 1970-01-01
          • 1970-01-01
          • 2013-12-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多