簡體   English   中英

使用sed,如何刪除與任何一組模式匹配的所有初始行?

[英]Using sed, how do I delete all initial lines that match any of a set of patterns?

我正在尋找使用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所有模式,只需使用循環:done;n;bdone打印其余的: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
{ ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM