【问题标题】:Use AWK in Expect script在 Expect 脚本中使用 AWK
【发布时间】:2015-08-11 02:55:05
【问题描述】:

我正在尝试制作一个期望脚本,并且在脚本中需要 AWK 或 sed。

我还有一个像这样的名为 TimeBased_CLI.ini 的文件。

192.168.1.22 is rhost
2022 is port

我的目标是将文件作为变量放入脚本中。

这是我当前的错误脚本

#!/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"

它给了我

-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)

我该如何解决?

# [解决了]

我使用的最后一个命令是这样的:

set rhost "[exec awk {$NF ~ /rhost/ {print $1;}} TimeBased_CLI.ini]"

该命令的shell格式为:

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

【问题讨论】:

  • 语法高亮正确吗?

标签: bash awk pipe expect


【解决方案1】:

单引号不是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

参考:Frequently Made Mistakes in Tcl

【讨论】:

  • 谢谢 只需将 '' 替换为 {} 即可解决我的问题。不需要 /$1
【解决方案2】:

只需使用所有 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"
}

【讨论】:

    猜你喜欢
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多