使用grep在两个子字符串之间提取字符串

时间:2017-10-27 14:12:17

标签: regex unix grep

以下摘录几乎是我想要的,但不完全是:

echo 'pie(x=x,labels=c("5.3 %","2.8 %","1.5 %","5.2 %","2.9 %","2.3 %","7.9 %","16.9 %","19.5 %","27.5 %","8.3 %"),main="ChIP",col=c("#445FA2","#EB9D86","#799F7A","#6C527F","#5FA1C1","#E8BB77","#A8C5EF","#FDCDB9","#C6E6B5","#F1D5EE","#B4E1F6"),clockwise=TRUE,border=FALSE,radius=0.9,cex=0.8,init.angle=90,density=100)'|grep -oP '(?<=").*?(?= %)'

输出是:

5.3
,"2.8
,"1.5
,"5.2
,"2.9
,"2.3
,"7.9
,"16.9
,"19.5
,"27.5
,"8.3

请您告诉我如何获得一个清洁剂&#39;输出如:

5.3
2.8
1.5
5.2
2.9
2.3
7.9
16.9
19.5
27.5
8.3

最好,请在上面的grep -oP上找到解决方案,但当然欢迎其他解决方案!

4 个答案:

答案 0 :(得分:1)

如果你只想要0-9和&#34;。&#34;你可以使用的字符:

grep -oP '(?<=")[\d\.]*?(?= %)'

而不是

grep -oP '(?<=").*?(?= %)'

注意:Perl中的\ d匹配0-9而不是 。在Perl中匹配任何字符,因此您将其转义为文字句点字符

答案 1 :(得分:0)

带空格的简单匹配数字适用于您想要的输出。

 grep -oP '[0-9]+.[0-9]+ '

如果小数点与%之间没有空格,这也可以,

grep -oP '[0-9]+.[0-9]+.*?(?=%)'

答案 2 :(得分:0)

用以下内容扩展它:

... | grep -Eo "[0-9]+\.[0-9]+"

如果您只是寻找“数字点数”或使用:

... | grep -Eo "[0-9]+\.[0-9]+|[0-9]+"

所有数字之间可能有一个点。

答案 3 :(得分:0)

GNU awk 解决方案:

s='pie(x=x,labels=c("5.3 %","2.8 %","1.5 %","5.2 %","2.9 %","2.3 %","7.9 %","16.9 %","19.5 %","27.5 %","8.3 %"),main="ChIP",col=c("#445FA2","#EB9D86","#799F7A","#6C527F","#5FA1C1","#E8BB77","#A8C5EF","#FDCDB9","#C6E6B5","#F1D5EE","#B4E1F6"),clockwise=TRUE,border=FALSE,radius=0.9,cex=0.8,init.angle=90,density=100)'

awk -v FPAT='"[0-9]+\\.[0-9]+ %"' '{ for(i=1;i<=NF;i++) { gsub(/[^.0-9]+/,"",$i); print $i } }' <<<"$s"

输出:

5.3
2.8
1.5
5.2
2.9
2.3
7.9
16.9
19.5
27.5
8.3