使用 sed,如何删除与一组模式中的任何一个匹配的所有初始行



我希望使用 sed 删除文件中与一组模式匹配的所有初始行。但是,一旦没有任何模式匹配,文件的其余部分应不加修改地传递。

例如,如果模式为:

^s*#
^s*$

然后对于文件:

#!/bin/bash
# Some words
# The line above has spaces or tabs in it
    #
    # The above line has spaces before and after the #
main()
{ ... }
# Another comment

SED 脚本将生成:

main()
{ ... }
# Another comment

也就是说,在这种情况下,模式集会删除任何初始 Bash 注释、空行和仅包含空格的行。

虽然听到如何使用其他工具(例如awk(完成此操作可能很有趣,但我主要对涉及sed的解决方案感兴趣。

我正在寻找上述示例的特定解决方案,以及如何将其推广到一组任意模式的任何指导。

我的环境是:

  • CentOS 7.3 (3.10.0-514.6.1.el7.x86_64(
  • bash-4.2.46-21.el7_3.x86_64
  • sed-4.2.2-5.el7.x86_64

删除匹配的行,但是一旦您通过了所有模式,只需使用循环:done;n;bdone打印其余

下面是示例:

测试.c:

#!/bin/bash
# Some words
# The line above has spaces or tabs in it
    #
    # The above line has spaces before and after the #
DELETEME
main()
DELETEME - should stay
{ ... }

$ sed '/^s*#/d; /DELETEME/d; /^s*$/d; :done;n;bdone' test.c 
main()
DELETEME - should stay
{ ... }

相关内容

最新更新