Search code examples
regexfiletclexpect

Converting part of read line from file to a variable in tcl


I have a file which has something like this:

IPLIST: 10.10.10.1 10.10.10.2 # A bunch of IPs

#CMDS:
ping $ip

I want to use tcl to read the file and run the commands. I've been successful in reading the file, and create a list of IPs, and also create a list of commands. And I want to run the commands, for which I did:

#iplist is the list of IP formed from IPLIST in file
foreach ip $iplist {
 # cmdlist is the list of commands read from file
 foreach cmd $cmdlist {
  echo "$cmd\n"
 }
}

I was expecting the $ip in the command will get replaced by the ip variable in the first foreach loop. But, that is not happening. What I get is:

ping $ip

Is there a way I can get the $ip in the file get converted to the ip from the iplist as I run the foreach loop ? I did look at a whole bunch of examples here, but none which can be used in this situation Thank you for the help!


Solution

  • Try using subst:

    echo [subst -nobackslashes -nocommands $cmd]
    

    It will perform substitution on variables. I'm also using -nobackslashes and -nocommands there just in case there might be square parens which might not be what you want to execute, if there are any, but if you do want them to execute, then you can omit them.