期望:从命令的输出中提取负数

Expect: Extract negative number from command's output

我正在使用 expect 脚本执行命令,并想从输出中提取一个数字,我打算稍后在脚本中使用它。如果我只是在脚本中使用以下命令

$expect_out(buffer)

我得到以下命令和实际输出

# some_command | awk '{print }'
-2520

根据我在 Internet 上看到的示例,我修改了我的脚本以使用正则表达式来仅提取数字,但它似乎不起作用:

set prompt "(\$|#) $"

... Login code goes here

expect -re $prompt
send "some_command | awk '{print $2}'\r" --> Prints a negative number (not floating) i.e -2520
expect -re {"^-[0-9]\d*"}
set num $expect_out(0,string)
puts "Result : $num"

send "exit\r"

出于某种原因,我无法从缓冲区中提取数字 -2520。我得到的输出是:

# Result : # 

我做错了什么?

你应该这样写:

expect -re {[\r\n](-?[0-9]+)}
set num $expect_out(1,string)

示例:

[STEP 101] # cat foo.exp
set re_PS1 {bash-[.0-9]+[#$] $}

spawn bash --norc
expect -re $re_PS1

send "[lindex $argv 0]\r"
expect {
    -re {[\r\n](-?[0-9]+)} {
        set num $expect_out(1,string)
        exp_continue
    }
    -re $re_PS1
}

send "exit\r"
expect eof

puts "result: $num"
[STEP 102] # expect foo.exp 'expr 0 - 12345'
spawn bash --norc
bash-4.4# expr 0 - 12345
-12345
bash-4.4# exit
exit
result: -12345
[STEP 103] # expect foo.exp 'expr 12345'
spawn bash --norc
bash-4.4# expr 12345
12345
bash-4.4# exit
exit
result: 12345
[STEP 104] #