简体   繁体   English

在 Expect 脚本中使用 AWK

[英]Use AWK in Expect script

I'm trying to make a expect script and need AWK or sed in side the script.我正在尝试制作一个期望脚本,并且需要在脚本旁边使用 AWK 或 sed。

I also have a file named TimeBased_CLI.ini like this.我也有一个像这样的名为 TimeBased_CLI.ini 的文件。

192.168.1.22 is rhost
2022 is port

My goal is put the file into the script as variables.我的目标是将文件作为变量放入脚本中。

Here is my current wrong script这是我目前的错误脚本

#!/usr/bin/expect -f
set timeout 10

#INPUT Vars from TimeBased_CLI.ini file
set rhost "[exec grep rhost ./TimeBased_CLI.ini | awk "/[[:blank:]]*is[[:blank:]]*/ \{print \$1 \}"]"
send_user "$rhost\n"

It gives me它给了我

-sh-4.1$ ./test.exp
invalid command name ":blank:"
    while executing
":blank:"
    invoked from within
"[:blank:]"
    invoked from within
"exec grep rhost ./TimeBased_CLI.ini | awk "/[[:blank:]]*is[[:blank:]]*/ \{print \$1 \}""
    invoked from within
"set rhost "[exec grep rhost ./TimeBased_CLI.ini | awk "/[[:blank:]]*is[[:blank:]]*/ \{print \$1 \}"]""
    (file "./test.exp" line 5)

How can I fix it?我该如何解决?

# [Solved] # [解决了]

The final command I use is like:我使用的最终命令是这样的:

awk '$NF ~ /rhost/ {print $1;}' TimeBased_CLI.ini

The shell format of this command is:该命令的shell格式为:

 awk '$NF ~ /rhost/ {print $1;}' TimeBased_CLI.ini

Single quotes are not the quoting mechanism for Tcl , so brace your AWK expressions.单引号不是Tcl的引用机制,因此请使用 AWK 表达式。

% set awkCmd {/[[:blank:]]*is[[:blank:]]*/ {print $1}}
/[[:blank:]]*is[[:blank:]]*/ {print $1}
% set rhost [exec grep rhost ./TimeBased_CLI.ini | awk $awkCmd]
192.168.1.22

Reference: Frequently Made Mistakes in Tcl参考: Tcl 中的常见错误

Just use the all Tcl solution.只需使用所有 Tcl 解决方案。

set fd [ open ./TimeBased_CLI.ini "r" ]
set buffer [read $fd ]
catch { close $fd }

# Assuming the line we are looking for
# is "rhost is <some IP address>"
if { [ regexp {rhost[ ]*is[ ]*([0-9\.]+)} $buffer match rhost] == 0 } {
    send_user "rhost not found!\n"
} else {
    send_user "rhost is $rhost\n"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM