Search code examples
bashawkpipeexpect

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:

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

The shell format of this command is:

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

Solution

  • 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