使用 sed,如何删除与一组模式中的任何一个匹配的所有初始行?
Using sed, how do I delete all initial lines that match any of a set of patterns?
我希望使用 sed 删除文件中与一组模式匹配的所有初始行。但是,一旦 none 个模式匹配,文件的其余部分应该不加修改地通过。
例如,如果模式是:
^\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
也就是说,在这种情况下,模式集会删除任何 initial 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
打印其余部分
示例如下:
test.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
{ ... }
我希望使用 sed 删除文件中与一组模式匹配的所有初始行。但是,一旦 none 个模式匹配,文件的其余部分应该不加修改地通过。
例如,如果模式是:
^\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
也就是说,在这种情况下,模式集会删除任何 initial 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
示例如下:
test.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
{ ... }