在bash中使用regex解析分隔数组

在bash中使用regex解析分隔数组,regex,bash,svg,grep,pcre,Regex,Bash,Svg,Grep,Pcre,我有一个包含以下行的文件: 我需要提取以下值: 287470 509 459 471 我目前正在使用此代码: grep-oP'(?)'“file.svg”| grep-oP'(?sed解决方案可以是 $ sed -r '/points=/ s/[^,]+,?([0-9]*)/\1 /g' input 287 470 509 459 471 或 为了更好的处理 $ sed -r '/points=/ s/.*points=("[^"]+").*/\1/g; s/[^,]+,?([0-9]*)

我有一个包含以下行的文件:

我需要提取以下值:

287470 509 459 471

我目前正在使用此代码:


grep-oP'(?)'“file.svg”| grep-oP'(?sed解决方案可以是

$ sed -r '/points=/ s/[^,]+,?([0-9]*)/\1 /g' input
287 470 509 459 471 

为了更好的处理

$ sed -r '/points=/ s/.*points=("[^"]+").*/\1/g; s/[^,]+,?([0-9]*)/\1 /g' input
287 470 509 459 471 

如果您只是解析这样一行代码,那么可以使用
XML::Simple
,如下所示:

perl -MXML::Simple -lwe'$x = XMLin(<>); print $x->{points};' file.svg
当使用
Data::Dumper
打印时,从该行解析的
$x
中的整个结构如下所示:

$VAR1 = {
          'points' => '0,287 100,470 200,509 300,459 400,471',
          'id' => 'graph'
        };

请注意,如果输入内容比您在问题中指出的内容更复杂,您可能需要对其进行预处理。

这是XML,所以请将其解析为XML

use XML::Twig;
my $twig = XML::Twig -> new -> parse ( '<polyline id="graph" points="0,287 100,470 200,509 300,459 400,471"/>' );
print $twig ->  root -> {'att'} -> {'points'};
您可以使用gnu awk:

awk -v RS='points="[^"]+"' 'RT{s=RT; gsub(/[^[:digit:], ]|[[:digit:]]+,/, "", s); 
   print s}' file
287 470 509 459 471

awk
应能:

awk -F\" '/points/ {gsub(/[0-9]+,/,"",$4);print $4}' file
287 470 509 459 471
如果线路上的位置发生变化,请执行以下操作:

awk -F"points=" 'NF==2{gsub(/[0-9]+,|[^0-9 ]/,"",$2);print $2}' file
287 470 509 459 471

我忘了提到那个平台上没有
perl
。我标记它是因为
-P
开关…嗯,如果行是这样的:
,那么上面的sed生成:
2,4287470509471
@anubhava我也添加了它。希望不会留下更多的漏洞;)
awk -F\" '/points/ {gsub(/[0-9]+,/,"",$4);print $4}' file
287 470 509 459 471
awk -F"points=" 'NF==2{gsub(/[0-9]+,|[^0-9 ]/,"",$2);print $2}' file
287 470 509 459 471