如何迭代几个预期的行

时间:2016-04-25 22:11:52

标签: linux tcl expect

我正在尝试从CLI解析一些输出并迭代它。输出类似于以下内容,我想迭代每个id以对这些对象做更多的事情。

  

OVM>列表ServerPool
  命令:list ServerPool
  状态:成功
  数据:
  id:123456789名称:pool1
  id:987654321 name:pool2

我正在尝试以下代码但由于某种原因它在打印第二个ID后挂起。我认为这与exp_continue有关,但我不太清楚期望。另外,我正在为只有2个ID的情况做这个简单的解决方案,因为我不知道如何推广它并且一次获得几行以便稍后迭代它们并发送更多命令。

我尝试在第二个ID被打印后添加一个退出但它没用,就像它试图保持期待的东西并挂在那里。我不知道如何在那时取消exp_continue。

expect "OVM> " {
    send "list ServerPool\r"
    expect {
        -re "  id:(.*?)  (.*?)\n\r" {
            send_user "$expect_out(1,string)\n"; exp_continue
        }
        -re "  id:(.*?)  (.*?)\n\r" {
            send_user "\n$expect_out(1,string)\n";
        }
    }
}

send "exit\r"
expect eof

1 个答案:

答案 0 :(得分:1)

参见以下示例:

% cat foo.exp
spawn -noecho cat file

set idNames {}
expect {
    -re {id:([0-9]+) name:([[:alnum:]]+)} {
        set idName [list $expect_out(1,string) $expect_out(2,string)]
        lappend idNames $idName
        exp_continue
    }
    "OVM>" {}
}   

send_user "==== result: ====\n"
foreach idName $idNames {
    lassign $idName id name
    send_user "id=$id name=$name\n"
}
% cat file
OVM> list ServerPool
Command: list ServerPool
Status: Success
Data: 
id:123456789 name:pool1
id:234567890 name:pool2
id:345678901 name:pool3
id:456789012 name:pool4
id:567890123 name:pool5
id:678901234 name:pool6
OVM> other command
% expect foo.exp
OVM> list ServerPool
Command: list ServerPool
Status: Success
Data: 
id:123456789 name:pool1
id:234567890 name:pool2
id:345678901 name:pool3
id:456789012 name:pool4
id:567890123 name:pool5
id:678901234 name:pool6
OVM> other command
==== result: ====
id=123456789 name=pool1
id=234567890 name=pool2
id=345678901 name=pool3
id=456789012 name=pool4
id=567890123 name=pool5
id=678901234 name=pool6
%
相关问题