【问题标题】:Output text between two patterns on the same line using sed command使用 sed 命令在同一行上的两个模式之间输出文本
【发布时间】:2018-08-24 14:16:44
【问题描述】:

我试过这个命令,但它只能在一定程度上起作用。

输入文件内容:

this is begin not sure what is wrong end and why not

命令:

cat file | sed 's/.*begin \(.*\)end/\1/'

输出:

not sure what is wrong and why not

所需的输出(请参阅下面的注释):

not sure what is wrong 
  1. 我的 sed 命令搜索第一个模式和第二个模式,但忽略了第二个模式并打印文本。但是,它也会打印该行的其余部分,why not。我不想打印第二个模式之后的内容,只打印两个模式之间的内容。我不知道该怎么做。
  2. 如果同一行有两个end怎么办?

有人可以提供并解释该命令吗?

【问题讨论】:

  • 你可以使用sed 's/.*begin \(.*\) end.*/\1/' file

标签: bash search sed replace


【解决方案1】:

问题是您只替换匹配的内容,而不是end 之后的其他文本。只需添加.*

txt='this is begin not sure what is wrong end and why not'

sed 's/.*begin \(.*\)end.*/\1/' <<< "$txt"

给予:

not sure what is wrong 

【讨论】:

    【解决方案2】:

    关注sed 可能对您有所帮助。

    echo "this is begin not sure what is wrong end and why not" | sed 's/.*begin //;s/ end.*//'
    

    【讨论】:

      【解决方案3】:

      对于您当前的输入,您可以使用sed

      sed 's/.*begin \(.*\) end.*/\1/' file
      

      not sure what is wrong
      

      区别在于在end 之后使用.* 匹配最后一个end 之后的文本并替换为丢弃。


      但是对于您的第二部分,如果有两个 end 单词,sed 命令将无法正常工作,因为它会找到最后一个 end,因为 .*贪婪匹配

      例如,如果您的输入是:

      this is begin not sure what is wrong end and why not end
      

      那么关注awk 会更好:

      awk -F 'begin | end' '{print $2}' file
      

      not sure what is wrong
      

      【讨论】:

      • thx - 两者都有效 - thx 在回答之前阅读整个线程
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 2018-10-04
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多