期望 spawn 命令:在字符串中转义换行符(\n)

期望 spawn 命令:在字符串中转义换行符(\n)

我正在尝试使用 expect 与 MATLAB 控制台交互。目前我有:

#!/usr/bin/expect -f


spawn {*}/usr/bin/run.sh matlab -r "fprintf(1, \"The identifier was:%s\\\\n\", \"hello\")"

expect {
    "The identifier is hello" {
        return
    }
    timeout {
        exit 7
    } eof {
        return
    }
}

但这会出现错误:

./create_meta_file.exp 
spawn /usr/bin/run.sh matlab -r fprintf(1, "The identifier was:%s\\n", "hello")

MATLAB is selecting SOFTWARE OPENGL rendering.
                   < M A T L A B (R) >
                                                                      Copyright 1984-2022 The MathWorks, Inc.
                                                                 R2022a Update 2 (9.12.0.1956245) 64-bit (glnxa64)
                                                                                   May 11, 2022

 
To get started, type doc.
For product information, visit www.mathworks.com.
 
 fprintf(1, "The identifier was:%s
            |
Error: String is not terminated properly.

如果我在预期脚本中使用\n\\n或者 \\\n代替,我会得到:\\\\n

spawn /usr/bin/run.sh matlab -r fprintf(1, "The identifier was:%s
", "hello")
MATLAB is selecting SOFTWARE OPENGL rendering.
/usr/local/bin/matlab: 1: eval: Syntax error: Unterminated quoted string

任何指示都将不胜感激。

答案1

应该工作:

spawn /usr/bin/run.sh matlab -r "fprintf(1, \"The identifier was:%s\\n\", \"hello\")"
# .................................................................^^

虽然我建议使用 Tcl 的非插值引号来简化:

spawn /usr/bin/run.sh matlab -r {fprintf(1, "The identifier was:%s\n", "hello")}
# ..............................^..............................................^

这里不需要前导{*}:它仅适用于“/usr/bin/run.sh”,不需要扩展为单独的单词。

相关内容