1
#!/usr/bin/expect -f
set cmd "abc def ghi lkj"
set log [ expr echo ${cmd// /_} ]

I would like to log variable as ghi_lkj

first I wast trying to replace all spaces with underscores and then remove first two words.

I want to do it only in expect script not shell script.

please suggest how to do. Thanks in Advance.

0

1 Answer 1

2

expect is a TCL interpreter, ${cmd// /_} is a Korn shell parameter expansion operator. TCL is not ksh, or any shell for that matters.

After reading the expect man page, your next step should be to study the TCL documentation. See for instance https://tcl.tk/doc/ though you can also install the man pages on your system for your version of TCL (you may need to install a tcl-doc package).

Here to do character substitutions, you can use TCL's string map for instance:

set cmd "abc def ghi lkj"
set log [string map {" " _} $cmd]
puts $log

Or consider that $cmd as a list and join with _:

set cmd "abc def ghi lkj"
set log [join $cmd _]
puts $log

Which would output abc_def_ghi_lkj.

If you want ghi_lkj, then, that's not only SPC to _ you want to do.

Possibly you want the last two words joined with _ or all but the first 2 joined with _:

set cmd "abc def ghi lkj"
set log [join [lrange $cmd 2 end] _]
puts $log
3
  • Excellent advice. Generally you want to explicitly convert strings to lists before using list commands (in case the strings does not contain a valid list): set log [join [lrange [split $cmd] 2 end] _] Nov 1, 2020 at 13:55
  • @glennjackman, true in the general case, but given the name of the variable (cmd), I take it it's meant to contain a list here. Nov 1, 2020 at 13:59
  • Thanks it's working perfectly.
    – bhr
    Nov 3, 2020 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.