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

后端 未结 12 2286
春和景丽
春和景丽 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:10

    GNU grep can also support positive & negative look-ahead & look-back: For your case, the command would be:

    echo "Here is a string" | grep -o -P '(?<=Here).*(?=string)'
    

    If there are multiple occurrences of Here and string, you can choose whether you want to match from the first Here and last string or match them individually. In terms of regex, it is called as greedy match (first case) or non-greedy match (second case)

    $ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*(?=string)' # Greedy match
     is a string, and Here is another 
    $ echo 'Here is a string, and Here is another string.' | grep -oP '(?<=Here).*?(?=string)' # Non-greedy match (Notice the '?' after '*' in .*)
     is a 
     is another 
    

提交回复
热议问题