【问题标题】:Remove a variety of lines in a text file删除文本文件中的多行
【发布时间】:2009-10-24 10:10:09
【问题描述】:

我一直在尝试实现一个从 wordnet 的在线数据库读取的 bash 脚本,并且一直想知道是否有一种方法可以用一个命令删除各种文本文件。

示例文件转储:

**** Noun ****
(n)hello, hullo, hi, howdy, how-do-you-do (an expression of greeting) "every morning they exchanged polite hellos"
**** Verb ****
(v)run (move fast by using one's feet, with one foot off the ground at any given time) "Don't run--you'll be out of breath"; "The children ran to the store"
**** Adjective ****
(adj)running ((of fluids) moving or issuing in a stream) "as mountain stream with freely running water"; "hovels without running water"

我只需要删除描述语法方面的行,例如

**** Noun ****
**** Verb ****
**** Adjective ****

这样我就有了一个只有单词定义的干净文件:

(n)hello, hullo, hi, howdy, how-do-you-do (an expression of greeting) "every morning they exchanged polite hellos"
(v)run (move fast by using one's feet, with one foot off the ground at any given time) "Don't run--you'll be out of breath"; "The children ran to the store"
(adj)running ((of fluids) moving or issuing in a stream) "as mountain stream with freely running water"; "hovels without running water"

语法术语周围的 * 符号让我在 sed 中绊倒了。

【问题讨论】:

    标签: linux sed awk grep cat


    【解决方案1】:

    如果您想仅根据这些行的内容从文件中选择整行,grep 可能是最合适的可用工具。但是,某些字符,例如您的星号,对grep 具有特殊含义,因此需要用反斜杠“转义”。这将只打印以四星和一个空格开头的行:

    grep "^\*\*\*\* " textfile
    

    但是,您希望保留 匹配的行,因此您需要 -v 选项用于 grep 这样做:打印 don 的行't 匹配模式。

    grep -v "\*\*\*\* " textfile
    

    这应该会给你你想要的。

    【讨论】:

    • 你的解释和第二段代码都帮助了我,达到了结果。
    【解决方案2】:
    sed '/^\*\{4\} .* \*\{4\}$/d'
    

    或者稍微宽松一点

    sed '/^*\{4\}/d'
    

    【讨论】:

      【解决方案3】:
       sed 's/^*.*//g' test | grep .
      

      【讨论】:

      • 你的也实现了解决方案 - 但你只是有点迟到了。两个答案都达到了问题的结果。
      【解决方案4】:
      # awk '!/^\*\*+/' file
      (n)hello, hullo, hi, howdy, how-do-you-do (an expression of greeting) "every morning they exchanged polite hellos"
      (v)run (move fast by using one's feet, with one foot off the ground at any given time) "Don't run--you'll be out of breath"; "The children ran to the store"
      (adj)running ((of fluids) moving or issuing in a stream) "as mountain stream with freely running water"; "hovels without running water"
      

      【讨论】:

        猜你喜欢
        • 2012-03-28
        • 2010-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 1970-01-01
        • 1970-01-01
        • 2018-06-03
        相关资源
        最近更新 更多