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 ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.