用正则表达式选择值

时间:2019-02-06 19:40:53

标签: regex bash sox

我对正则表达式一无所知,所以我想知道您是否只能从sox程序返回的文本中选择最大振幅值? 例如,在这种情况下,我只选择0.712219

Samples read:           6615000
Length (seconds):     75.000000
Scaled by:         2147483647.0
Maximum amplitude:     0.712219
Minimum amplitude:    -0.805969
Midline amplitude:    -0.046875
Mean    norm:          0.009264
Mean    amplitude:    -0.000027
RMS     amplitude:     0.043011
Maximum delta:         0.734100
Minimum delta:         0.000000
Mean    delta:         0.008353
RMS     delta:         0.041470
Rough   frequency:         6767
Volume adjustment:        1.241

4 个答案:

答案 0 :(得分:0)

^Maximum amplitude:\s*(-?\d\.\d+)\n

请参见here

  • ^代表行首。
  • Maximum amplitude:确保行正确
  • \s*零个或多个空格字符
  • ( )代表捕获组-您希望正则表达式返回的内容
  • -?意味着可选的减号
  • \d代表一位数字
  • \.代表小数位
  • \d+代表1个或多个数字
  • \n代表换行符-导致换行。

这是regex101.com生成的Perl:

use strict;

my $str = 'Samples read:           6615000
Length (seconds):     75.000000
Scaled by:         2147483647.0
Maximum amplitude:     0.712219
Minimum amplitude:    -0.805969
Midline amplitude:    -0.046875
Mean    norm:          0.009264
Mean    amplitude:    -0.000027
RMS     amplitude:     0.043011
Maximum delta:         0.734100
Minimum delta:         0.000000
Mean    delta:         0.008353
RMS     delta:         0.041470
Rough   frequency:         6767
Volume adjustment:        1.241';
my $regex = qr/^Maximum amplitude:\s*(-?\d\.\d+)\n/mp;

if ( $str =~ /$regex/g ) {
  print "Whole match is ${^MATCH} and its start/end positions can be obtained via \$-[0] and \$+[0]\n";
  # print "Capture Group 1 is $1 and its start/end positions can be obtained via \$-[1] and \$+[1]\n";
  # print "Capture Group 2 is $2 ... and so on\n";
}

# ${^POSTMATCH} and ${^PREMATCH} are also available with the use of '/p'
# Named capture groups can be called via $+{name}

Here是使用amp命名捕获组的示例。

^Maximum amplitude:\s*(?P<amp>-?\d\.\d+)\n

答案 1 :(得分:0)

perl -nle 'm{Maximum amplitude:\s+(-?\d?\.?\d+)} and print $1' file

0.712219

这将处理带负号的数字以及带负号的数字(不含小数点和任意位数)。

答案 2 :(得分:0)

我会在awk中这样做:

awk '/Maximum amplitude:/ { print $NF }' infile

这将通过匹配Maximum amplitude:的行进行过滤,然后打印该行的最后一个以空格分隔的字段。

答案 3 :(得分:0)

仅打印具有匹配项的行并修改该行。

sed -n '/Maximum amplitude/ s/.* //p' inputfile