简体   繁体   English

期望,sed和可变替代

[英]Expect, sed, and Variable Substitution

I'm calling an expect script from a bash script and passing an argument to be used for sed string replacement. 我打电话的expect从一个bash脚本脚本,并传递一个参数用于sed字符串替换。

But it errors out b/c of the variable in sed statement. 但是它会错误地消除sed语句中变量的b / c。 Any suggestions on how to fix this? 对于如何解决这个问题,有任何的建议吗? I've tried escape \\/ but no much success. 我尝试过逃脱\\/但是没有成功。

The parameter is passed successfully (cde) 参数成功传递(CDE)

The code: 编码:

#!/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 }

Error: 错误:

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

What's Broken 怎么了

The following is an invalid invocation: 以下是无效的调用:

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

It is invalid because: 这是无效的,因为:

  1. The quoted expression is not associated with the -e flag. 带引号的表达式不与-e标志关联。
  2. ${mount} may contain a newline or leading/trailing whitespace characters. ${mount}可能包含换行符或前导/尾随空格字符。

How to Fix It 如何修复

In order to fix your problems, you should: 为了解决您的问题,您应该:

  1. Switch your command line arguments. 切换命令行参数。
  2. Ensure that the -i flag is provided an argument (eg an empty string) so that it will work with a non-GNU sed. 确保为-i标志提供了一个参数(例如,空字符串),以便它将与非GNU sed一起使用。
  3. Strip any newlines or leading/trailing whitespace from your mount variable with string trim . 使用string trim挂载变量中删除所有换行符或前导/结尾空格。

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM