【问题标题】:Search for text between two patterns with multiple lines in between在两个模式之间搜索多行文本
【发布时间】:2016-04-30 19:38:54
【问题描述】:

我有一个简单的问题。我有一个文件包含:

more random text

*foo*
there
is 
random
text
here
*foo*

foo
even
more
random
text
here
foo
more random text

(为了澄清我想要从哪些部分得到结果,我在 foo 旁边添加了 *。* 不在文件中。)

我只想打印出 foo 的前 2 个实例之间的多行。

我尝试寻找让“foo”只出现一次然后将其删除的方法。但我没有走那么远。但是,我确实找到了使用以下方法删除所有“更多随机文本”的方法:sed '/foo/,/foo/p',但我找不到使用 sed 或 awk 仅匹配并打印输出的方法。

谁能帮帮我?

【问题讨论】:

    标签: regex bash awk sed


    【解决方案1】:

    使用 sed:

    $ sed -n '/foo/{:a;n;/foo/q;p;ba}' infile
    there
    is
    random
    text
    here
    

    解释:

    /foo/ {     # If we match "foo"
        :a      # Label to branch to
        n       # Discard current line, read next line (does not print because of -n)
        /foo/q  # If we match the closing "foo", then quit
        p       # Print line (is a line between two "foo"s)
        ba      # Branch to :a
    }
    

    一些 seds 抱怨单衬里的牙套;在这些情况下,这应该有效:

    sed -n '/foo/ {
        :a
        n
        /foo/q
        p
        ba
    }' infile
    

    【讨论】:

    • 感谢您对我的问题的贡献。喜欢 sed 和 awk 两者。不是他们的专家,但我很高兴我和其他人可以选择。
    【解决方案2】:

    由于检查“foo”(使用/foo/)的成本相对较高,因此以下内容避免了该检查,并且适用于所有名副其实的awks:

    awk 'c==2 {next} /foo/{++c;next} c==1' file
    

    【讨论】:

      【解决方案3】:
      $ awk '/foo/{++c;next} c==1' file
      there
      is
      random
      text
      here
      
      $ awk '/foo/{++c;next} c==3' file
      even
      more
      random
      text
      here
      

      或者使用 GNU awk for multi-char RS 你可以这样做:

      $ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==2' file
      there
      is
      random
      text
      here
      
      $ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==4' file
      even
      more
      random
      text
      here
      

      请参阅https://stackoverflow.com/a/17914105/1745001 了解条件为真后的其他打印方式。

      【讨论】:

      • 请解释其背后的逻辑
      • 你认为这意味着什么?我很乐意回答具体问题,但这有点像解释一个 Hello World 程序,所以在你需要帮助的地方知道。
      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      相关资源
      最近更新 更多