string - 如何使用 sed/grep在两个单词之间提取文本?

我正在尝试输出一个字符串,里面包含字符串两个单词之间的所有内容:

输入:


"Here is a String"

输出:

 
"is a"

 

使用:


sed -n '/Here/,/String/p'

时间:


sed -e 's/Here(.*)String/1/'


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

你可以单独在bash中去除字符串:


$ foo="Here is a String"
$ foo=${foo##*Here }
$ echo"$foo"
is a String
$ foo=${foo%% String*}
$ echo"$foo"
is a
$

如果你拥有包含PCRE的GNU grep,则可以使用零宽度断言:


$ echo"Here is a String" | grep -Po '(?<=(Here )).*(?= String)'
is a

这可能适用于你(GNU sed ):


sed '/Here/!d;s//&n/;s/.*n//;:a;/String/bb;$!{n;ba};:b;s//n&/;P;D' file 

如果你的文件很长且包含多行,则对第一行进行编号很有用:


cat file | nl | sed -n '/Here/,/String/p'

通过GNU awk


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

带有-P (perl-regexp )参数的grep支持K,这有助于丢弃以前匹配的字符,


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

如果你希望输出为is a,那么可以尝试下面的命令,


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

你可以使用1 (引用http://www.grymoire.com/Unix/Sed.html#uh-4 ):


echo"Hello is a String" | sed 's/Hello(.*)String/1/g'

括号内的内容将存储为1

...