简体   繁体   中英

Use AWK in Expect script

I'm trying to make a expect script and need AWK or sed in side the script.

I also have a file named TimeBased_CLI.ini like this.

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:

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

Single quotes are not the quoting mechanism for Tcl , so brace your AWK expressions.

% 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

Just use the all Tcl solution.

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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