Operating System - HP-UX
1837376 Members
3425 Online
110116 Solutions
New Discussion

Re: Expect question reading more than one var from same line from file

 
SOLVED
Go to solution
jerry1
Super Advisor

Expect question reading more than one var from same line from file

Does anyone have an example on how to read
more than one variable at the same time from
the same line from a file using expect. I can
open a file and read each line but what if
each line had more than one variable string.
For example. If I had a data file such as:

130.128.10.1 host1
130.128.10.2 host2

I would like to read both the ip and hostname
at the same time in an expect script loop and
do something with it. Then read the next line.
I have gone through the O'Reilly Expect book
but have not been able to find any examples
for doing this.

I can however do it by writing a wrapper ksh
script which reads and sets ip and host then
passing it to expect script as line arguments
as in the example below:

--------------
wrapper script

#!/bin/ksh

for i in `cat data`;do
ip=`echo "$i"|awk -F: '{print $1}'`
host=`echo "$i"|awk -F: '{print $2}'`
expectscript $ip $host
done

----------------
expectscript

#!/opt/expect/bin/expect

set argc [llength $argv]
for {set i 0} {$i<$argc} {incr i} {
set ip "[lindex $argv $i]"
incr i
set host "[lindex $argv $i]"
send "$ip $host\n" ;#For testing output.
}

4 REPLIES 4
G. Vrijhoeven
Honored Contributor
Solution

Re: Expect question reading more than one var from same line from file

Hi,

you could try:

cat file | while read IP HOST
do
echo " $HOST has $IP"
done

HTH,

Gideon
jerry1
Super Advisor

Re: Expect question reading more than one var from same line from file

That's not expect code.
curt larson_1
Honored Contributor

Re: Expect question reading more than one var from same line from file

how about something like this

scan "$argv" "%s %s" ip host

and why don't you do the whole thing in expect:

if {$argc != 1 } {
error "Usage: program filename"
}
set f [open [lindex $argv 0]
while {[gets $f line] >= 0} {
scan "$line" "%s %s" ip host
puts "$ip is $host"
}
flush $f
close $f
jerry1
Super Advisor

Re: Expect question reading more than one var from same line from file

Curt, looks like what I want and it works
okay but I had to put another ] for "set f"
line and comment out flush $f or I get the
error message after all data was displayed okay:

# test7 testdata
p08888 is 128.166.11.107
hr1c2c1 is 128.166.11.161
is2h3l1 is 128.166.11.42
en2d2l2 is 128.166.11.44
en2e2l2 is 128.166.11.45
en2d3l4 is 128.166.11.46
p01494 is 128.166.11.48
em1d5l1 is 128.166.11.49
ie2d6l1 is 128.166.13.120
mi1n11l4 is 128.166.13.128
channel "file4" wasn't opened for writing
while executing
"flush $f"
(file "test7" line 18)


Thanks for the syntax. Was driving me crazy.