【问题标题】:sed find pattern on line with another patternsed 找到与另一个模式一致的模式
【发布时间】:2013-11-07 15:32:03
【问题描述】:

我正在尝试从 <> 之间的文件中提取文本,但仅在以另一个特定模式开头的行上。

所以在一个看起来像这样的文件中:

XXX Something here  
XXX Something more here  
XXX <\Lines like this are a problem> 
ZZZ something <\This is the text I need> 
XXX Don't need any of this

我只想打印&lt;\This is the text I need&gt;

如果我这样做

sed -n '/^ZZZ/p' FILENAME

它会拉出我需要查看的正确行,但显然会打印整行。

sed -n '/<\/,/>/p' FILENAME prints way too much. 

我已经研究过分组并尝试过

sed -n '/^ZZZ/{/<\/,/>/} FILENAME

但这似乎根本不起作用。

有什么建议吗?他们将不胜感激。

(抱歉格式化,以前从未在这里发布过)

【问题讨论】:

    标签: regex bash sed


    【解决方案1】:
    sed -n '/^ZZZ/ { s/^.*\(<.*>\).*$/\1/p }'
    

    【讨论】:

      【解决方案2】:

      如果它不需要 sed 并且你有一个相当新的 grep,你可以使用 grep 的选项 -o 就像在

      grep '^ZZZ' | grep -o '<[^>]*>'
      

      【讨论】:

      • 因为 sed 和上面的人一起去了,但还是谢谢你。我会给你一票,但看来我太新了。
      【解决方案3】:

      awk 版本

      awk -F"<|>" '/^ZZZ/ {print "<"$2">"}' file
      <\This is the text I need>
      

      【讨论】:

        猜你喜欢
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-20
        • 2015-10-20
        相关资源
        最近更新 更多