如何让Expect根据脚本输出动态匹配并发送nice option对应编号
Dynamic Option Selection in Expect
Instead of hardcoding the option number, you can use Expect's regex pattern matching to dynamically capture the number associated with "nice option" from the script's output. This way, even if the option order changes, your script will still send the correct number.
Here's the updated Expect command:
expect -c ' spawn script.sh set timeout 3600 # Capture the digit before "nice option" using regex expect -re {(\d+) - nice option} set selected_number $expect_out(1,string) # Wait for the prompt and send the captured number expect "What number do you choose?" send "$selected_number\r" expect eof '
How this works:
- Regex Capture: The
-reflag tells Expect to use a regular expression. The pattern(\d+) - nice optionlooks for one or more digits (\d+) followed by- nice option, and captures those digits into the first match group. - Store the Number: We save the captured digit(s) into the variable
selected_numberusing$expect_out(1,string)(which accesses the first captured group from the regex match). - Respond to Prompt: Once we have the correct number, we wait for the "What number do you choose?" prompt and send the stored number followed by a carriage return (
\r).
This approach is robust to changes in the option order—whether "nice option" is at position 2, 4, or any other number, the script will automatically pick the right one.
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

