7

I am having troubles writing an expect script. I want to do something equivalent to the following bash instruction:

iplist=$(cat iplist.txt)

I've tried using set in all the ways that I know but it is still not working. Is there another way or is just that I'm not using it the right way?

set iplist=$(cat iplist.txt)
Andy Dalton
  • 13,654
  • 1
  • 25
  • 45
  • 1
    @don_crissti. Perfect! Sorry about that! I rolled it back ;-) –  Sep 21 '18 at 15:51
  • take a look at [*sexpect*](https://github.com/clarkwang/sexpect) with which you can write *Expect* scripts with shell code only. – UNIX.root Sep 22 '18 at 00:33

2 Answers2

7

Thanks for your answers, I've just found the solution in another post, in the function set the only missing was "exec", resulting the line:

set iplist [exec cat /root/iplist.txt]

And the expect file is going well, without any troubles!

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
  • 1
    If this is the solution, please mark it as such by clicking the ✔ to the left of this answer to indicate this. Welcome to U&L! – DopeGhoti Sep 21 '18 at 16:16
4

TCL can read(n) a file directly; this is both more efficient and more portable than forking out to some command.

#!/usr/bin/env expect

proc slurp {file} {
    set fh [open $file r]
    set ret [read $fh]
    close $fh
    return $ret
}

set iplist [slurp iplist.txt]

puts -nonewline $iplist

This also (if necessary) allows various open(n) or chan configure options to be specified, for example to set the encoding:

#!/usr/bin/env expect

package require Tcl 8.5

proc slurp {file {enc utf-8}} {
    set fh [open $file r]
    chan configure $fh -encoding $enc
    set ret [read $fh]
    close $fh
    return $ret
}

set data [slurp [lindex $argv 0] shiftjis]

chan configure stdout -encoding utf-8
puts $data

Which if saved as readfile and given somefile as input:

% file somefile
somefile: DBase 3 data file with memo(s) (1317233283 records)
% xxd somefile
00000000: 8365 8342 8362 834e 838b                 .e.B.b.N..
% ./readfile somefile
ティックル
% 
thrig
  • 34,333
  • 3
  • 63
  • 84