【问题标题】:remove all lines from file except one [closed]从文件中删除所有行,除了一个[关闭]
【发布时间】:2020-06-15 13:20:34
【问题描述】:

我有以下文件:

cat file.txt
User-agent: *
Disallow: /a-path*
Disallow: /000111/
Disallow: /*/my-path

User-agent: megaindex
Disallow: /

User-agent: DigitalPebble
Disallow: /

User-agent: EISSAB
Disallow: /

User-agent: archive.org_bot
Disallow: /

User-agent: dotbot
Disallow: /

我只需要保留 User-agent:* 块的指令和 Disallow 值,并删除下面的所有行。

所以在这种情况下,只应保留以下内容:

User-agent: *
Disallow: /a-path*
Disallow: /000111/
Disallow: /*/my-path

还有以下要删除的:

User-agent: megaindex
Disallow: /

User-agent: DigitalPebble
Disallow: /

User-agent: EISSAB
Disallow: /

User-agent: archive.org_bot
Disallow: /

User-agent: dotbot
Disallow: /

【问题讨论】:

  • 你想保留的总是第一个吗?
  • 您对问题的描述与您实际展示的示例不一致。

标签: linux awk sed scripting


【解决方案1】:

使用 GNU awk:

awk 'BEGIN{RS=ORS="\n\n"} $1=="User-agent:" && $2 == "*"' file

脚本依赖多行记录来一次解析每个文本块。

仅当User-agent: * 是文本块的第一部分时才打印行集。

【讨论】:

    【解决方案2】:

    Oliv 回答有效。 此外,我设法使用

    sed '/User\-agent\:\ .../,$d' < file.txt > newfile.txt
    

    基本上,sed 使用的是正则表达式,如果它找到User:agent: some multiple characters(使用“...”),它将删除下面的所有内容。

    【讨论】:

      【解决方案3】:

      另一种方式是使用grep:

      egrep 'User-agent:[[:space:]]*\*' file.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-22
        • 1970-01-01
        • 2015-09-02
        • 1970-01-01
        • 2014-01-04
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        相关资源
        最近更新 更多