More On The timed–read Script
In Chapter 3 (p. 77), I defined an Expect script called timed-read. Called from the shell with the maximum number of seconds to wait, the script waits for a string to be entered, unless the given time is exceeded. Here it is again:
set timeout $argv
expect "\n" {
send [string trimright "$expect_out(buffer)" "\n"]
}
In that earlier example I used "string trimright" to trim off the newline. It is possible for the expect command to do this in the pattern matching process, but not with glob patterns. I will use a regular expression to rewrite the script above without using the string command.
# timed read using a regular expression
set timeout $argv
expect -re "(.*)\n" {
send $expect_out(1,string)
}In the expect command, the -re flag declares the following pattern to be a regular expression instead of a glob pattern. As before, the pattern is quoted with double quotes. The pattern itself is:
(.*)\n
This matches any string of characters followed by a "\n“. All the characters except for the \n get stored in expect_out(1,string). Since the pattern is successfully matched, the action is executed. The action is to send all the characters in $expect_out(1,string) to the standard output. Of course, these characters are exactly what was just typed without the terminating "\n“.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access