How to use sed/grep to extract text between two words?

后端 未结 12 2332
春和景丽
春和景丽 2020-11-22 05:25

I am trying to output a string that contains everything between two words of a string:

input:

\"Here is a String\"

output:

12条回答
  •  感情败类
    2020-11-22 06:13

    Through GNU awk,

    $ echo "Here is a string" | awk -v FS="(Here|string)" '{print $2}'
     is a 
    

    grep with -P(perl-regexp) parameter supports \K, which helps in discarding the previously matched characters. In our case , the previously matched string was Here so it got discarded from the final output.

    $ echo "Here is a string" | grep -oP 'Here\K.*(?=string)'
     is a 
    $ echo "Here is a string" | grep -oP 'Here\K(?:(?!string).)*'
     is a 
    

    If you want the output to be is a then you could try the below,

    $ echo "Here is a string" | grep -oP 'Here\s*\K.*(?=\s+string)'
    is a
    $ echo "Here is a string" | grep -oP 'Here\s*\K(?:(?!\s+string).)*'
    is a
    

提交回复
热议问题