Skip to Content
Exploring Expect
book

Exploring Expect

by Don Libes
December 1994
Intermediate to advanced
606 pages
16h 7m
English
O'Reilly Media, Inc.
Content preview from Exploring Expect

Matching One Line And Only One Line

Matching a single line is such a common task that it is worth getting very familiar with it. The one-line script on page 131 matches a single line and this same technique will show up in many more scripts so it is worth examining closely here.

Suppose you want to search for a file in the file system with the string "frob" at the beginning of the name. There may be many files named "frob" (well, maybe not). You are just interested to know if there is at least one. The obvious tool to use is find. Unfortunately, find provides no control over the number of files it finds. You cannot tell it to quit after one. Here is an Expect script to do just that:

spawn find . -name "frob*" -print
set timeout −1
expect -re "\[^\r]*\r\n"

The script starts by spawning the find command. The timeout is disabled since this could be a very long running command. The expect pattern waits for one complete line to appear, and then the script exits. This works because the range waits for any character that is not a \r and the * waits for any number of them—that is, any number of characters that are not \r’s. The second \r both allows and forces a single \r. Finally the \n matches the linefeed in the carriage-return linefeed sequence. The only thing that can be matched is a single line.

Without Expect, it is possible to get find to kill itself by saving its process id in a file and then forking the kill command from an -exec clause in the find. However, doing this is fairly ...

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.
Start your free trial

You might also like

AI Agents in Action

AI Agents in Action

Micheal Lanham
Learning Go

Learning Go

Jon Bodner

Publisher Resources

ISBN: 9781565920903Supplemental ContentErrata Page