Expect、sed 和变量替换

Expect, sed, and Variable Substitution

我正在从 bash 脚本调用 expect 脚本并传递一个用于 sed 字符串替换的参数。

但是它在 sed 语句中出错了 b/c 变量。对于如何解决这个问题,有任何的建议吗?我试过逃脱 \/ 但没有成功。

参数传递成功(cde)

代码:

#!/usr/bin/expect -f
# ./sshlogin.exp uptime
set hosts {myhost.com}
set user root
set password xxxx
set mount [lindex $argv 0]
foreach vm $hosts {
    set timeout -1
    # now ssh
    spawn ssh $user@$vm -o StrictHostKeyChecking=no
    match_max 100000 # Look for passwod prompt
    expect "*?assword:*"
    # Send password aka $password
    send -- "$password\r"
    # send blank line (\r) to make sure we get back to gui
    expect "]# "
    send "sed -e -i 's/abc/${mount}/g' /my/files.new\r"
    expect "]# "
    sleep 1
    send -- "exit\r"
expect eof }

错误:

# sed -e 's/abc/cde
> /g' /my/files.new
sed: -e expression #1, char 37: unterminated `s' command

什么坏了

以下是无效调用:

sed -e -i 's/abc/${mount}/g'

无效,因为:

  1. 引用的表达式与 -e 标志无关。
  2. ${mount} 可能包含换行符或 leading/trailing 空白字符。

如何修复

为了解决您的问题,您应该:

  1. 切换你的命令行参数。
  2. 确保为 -i 标志提供一个参数(例如空字符串),以便它可以与非 GNU sed 一起使用。
  3. 使用 string trim.
  4. mount 变量中删除任何换行符或 leading/trailing 空格

例如:

set mount [string trim [lindex $argv 0]]
# ...
send "sed -i'' -e 's/abc/${mount}/g' /my/files.new\r"