如何从期望中删除特殊字符?

时间:2016-04-18 12:28:57

标签: bash scripting expect

所以我使用下一个expect脚本来获取交换机的running-config,然后将其保存到文件中:

#!/usr/bin/expect

set timeout 9
set username [lindex "foo"]
set password [lindex "bar"]
set hostname [lindex "1.2.3.4"]

spawn ssh -q $username@$hostname

expect {
  timeout { send_user "\nTimeout!\n"; exit 1 }
  "*assword"
}

send "$password\n"

expect {
  timeout { send_user "\nWrong password\n" ; exit 1 }
  "switch-00>"
}

send "enable\n"

expect {
  "switch-00#"
}

send "show running-config\n"
log_file -noappend log.txt

expect {
  -ex "--More--" { send -- " "; exp_continue }
  "*#" { log_file; send "exit\r" }
}

send "exit\n"

close

除此之外,它应该正常工作:

--More--^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H^H ^H
每次出现在log.txt中的

" - 更多 - "得到印刷。

删除" - 更多 - "这不是问题。后来使用bash,但如果我这样做:

grep "^H" log.txt

没有输出,所以我无法将其删除,因为它不匹配。

如果可能的话,我试图找到一种不用expect输出特殊字符的方法,但是没有找到,所以我在这里问以防万一有人知道。

使用bash的解决方案可以帮助我,但优先使用expect

1 个答案:

答案 0 :(得分:1)

您可以使用bash tr实用程序。来自man页面

NAME
tr -- translate characters

DESCRIPTION
The tr utility copies the standard input to the standard output with sub-
situation or deletion of selected characters.

SYNOPSIS
tr [-Ccsu] string1 string2
tr [-Ccu] -d string1

-C     Complement the set of characters in string1, that is ``-C ab''
       includes every character except for `a' and `b'.

-c     Same as -C but complement the set of values in string1.

-d     Delete characters in string1 from the input.

To Strip out non-printable characters from file1.

tr -cd "[:print:]\n" < file1   # This is all you need.