2017-06-15 11 views
1

私はexpectスクリプトを使用してコマンドを実行していますが、後でスクリプトで使用する数値を出力から抽出したいとします。私はちょうど私のスクリプトExpect:コマンドの出力から負の数を抽出する

$expect_out(buffer) 

で次のコマンドを使用している場合、私は、コマンドと同様に、私はインターネット上で見た例に基づいて実際の出力

# some_command | awk '{print $2}' 
-2520 

を持って、次を取得し、私は私のスクリプトを修正ただ数を抽出するために正規表現を使用するが、それは動作していないよう:

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 : # 

私は間違っていますか?

+0

あなたは正規表現から '" '取り外す必要があります:'期待-re {?^ - \ D +} ' – komar

+0

@komarを - '{^ - ?\ d +}'は動作しません。https://stackoverflow.com/questions/40498940/expect-script-not-sending-commands-after-successful-ssh-login/40499422#40499422 – pynexj

答えて

0

あなたはこのように書くshoul:

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] # 
+0

ありがとうございました。それはトリックをした – smokinguns

関連する問題