Bash 使用sed命令在同一行上的两个模式之间输出文本

Bash 使用sed命令在同一行上的两个模式之间输出文本,bash,search,sed,replace,Bash,Search,Sed,Replace,我尝试过这个命令,但它只在一定程度上起作用 输入文件内容: 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 所需输出(请参见以下注释): sed命令搜索第一个模式和第二个模式,但忽略第二个模式并打印文本。但是,它也会打印行的其余部分,为什么不。我不想打印第二个图案之后

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

输入文件内容:

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
所需输出(请参见以下注释):

  • sed命令搜索第一个模式和第二个模式,但忽略第二个模式并打印文本。但是,它也会打印行的其余部分,
    为什么不
    。我不想打印第二个图案之后的内容,只想打印两个图案之间的内容。我不知道该怎么做
  • 如果同一行上有两个
    end
    ,该怎么办

  • 有人能提供并解释该命令吗?

    问题是,您只替换匹配的内容,而不是
    结束后的其他文本。只需添加一个
    *

    txt='this is begin not sure what is wrong end and why not'
    
    sed 's/.*begin \(.*\)end.*/\1/' <<< "$txt"
    

    下面的
    sed
    可能会对您有所帮助

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

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

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

    区别在于在
    end
    之后使用
    *
    ,它匹配最后一个
    end
    之后的文本,并在替换中丢弃


    但是,对于第二部分,如果有两个
    end
    字,
    sed
    命令将无法正常工作,因为它将查找最后一个
    end
    ,这是由于
    *
    贪婪匹配

    e、 g如果您的输入是:

    this is begin not sure what is wrong end and why not end
    
    那么下面的
    awk
    会更好:

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


    您可以使用
    sed的/*begin\(.*\)end.*/\1/'文件
    thx-tware-work-thx在解析之前读取整个线程
    not sure what is wrong
    
    this is begin not sure what is wrong end and why not end
    
    awk -F 'begin | end' '{print $2}' file
    
    not sure what is wrong