[英]Using sed, how do I delete all initial lines that match any of a set of patterns?
I'm looking to use sed to delete all of the initial lines in a file that match a set of patterns. 我正在寻找使用sed删除文件中与一组模式匹配的所有初始行。 But, once none of the patterns are matched, the rest of the file should be passed through unmodified. 但是,一旦没有任何一种模式匹配,文件的其余部分应通过未修改的方式传递。
For example, if the patterns are: 例如,如果模式是:
^\s*#
^\s*$
Then for the file: 然后对于文件:
#!/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
the sed script would generate: sed脚本将生成:
main()
{ ... }
# Another comment
That is, in this case the set of patterns removes any initial Bash comments and, blank lines, and lines that just have whitespace in them. 也就是说,在这种情况下,模式集将删除所有初始的 Bash注释以及空白行和仅包含空格的行。
While it might be interesting to hear how this might be done with other tools (such as awk
), I am mainly interested in solutions involving sed
. 听到使用其他工具(例如awk
)如何完成此工作可能会很有趣,但我主要对涉及sed
解决方案感兴趣。
I'm looking for a specific solution to the example above as well as any guidance as to how to generalize this for a set of arbitrary patterns. 我正在寻找上述示例的特定解决方案,以及有关如何将其概括为一组任意模式的任何指导。
My environment is: 我的环境是:
Delete lines that do match, but once you get past all the patterns, just print the rest using the loop :done;n;bdone
删除确实匹配的行,但是一旦您:done;n;bdone
所有模式,只需使用循环:done;n;bdone
打印其余的:done;n;bdone
Here's the example: 这是示例:
test.c: 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
{ ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.