Tcl 将由空格分隔的线拆分为数组

Tcl 将由空格分隔的线拆分为数组,tcl,ns2,Tcl,Ns2,我有一个包含程序输出的文本文件。它是这样写的: 1 2 23 24 54 21 87 12 我需要输出为 arr[1]=2 arr[23]=24 arr[54]=21 arr[87]=12 等等 每行用空格隔开。如何使用TCL将这些行解析为如上所述的数组格式?(顺便说一下,我是为NS2这么做的)您可以在BASH中使用它: declare -A arr while read -r k v ; do arr[$k]=$v done < file 使用awk: awk '{ pri

我有一个包含程序输出的文本文件。它是这样写的:

1 2
23 24
54 21
87 12
我需要输出为

arr[1]=2
arr[23]=24
arr[54]=21
arr[87]=12
等等


每行用空格隔开。如何使用TCL将这些行解析为如上所述的数组格式?(顺便说一下,我是为NS2这么做的)

您可以在BASH中使用它:

declare -A arr

while read -r k v ; do
   arr[$k]=$v
done < file
使用awk:

awk '{ print "arr[" $1 "]=" $2 }' filename

您提到了每一行都是用空格分隔的,但给出了用新行分隔的内容。我假设,每一行用新行分隔,在每一行中,数组索引及其值用空格分隔

如果您的文本文件仅包含以下给出的文本

1 2
23 24
54 21
87 12
然后,首先将整个文件读入字符串

set fp [open "input.txt" r]
set content [ read $fp ]
close $fp
现在,使用
数组集
我们可以轻松地将它们转换为数组

# If your Tcl version less than 8.5, use the below line of code
eval array set legacy {$content}
foreach index [array names legacy] {
    puts "array($index) = $legacy($index)"
}

# If you have Tcl 8.5 and more, use the below line of code
array set latest [list {*}$content]
  foreach index [array names latest] {
    puts "array($index) = $latest($index)"
}

假设您的文件包含一些其他内容以及这些输入内容,那么您可以使用
regexp
单独获取这些内容,并且可以使用经典方法将元素逐个添加到数组中。

当您说“使用TCL”时,您的意思是“使用TCL语法”,对吗?否则我就不明白为什么要添加bash和awk标记。
list{*}$content
提供原始的
$content
。只要
数组设置最新的$content
就足够了。@PeterLewerin:谢谢你,彼得!。我想通过以列表格式提供它来避免任何可能的问题,这就是为什么我添加了
list
您仍然可以以完全相同的格式获得完全相同的内容。
# If your Tcl version less than 8.5, use the below line of code
eval array set legacy {$content}
foreach index [array names legacy] {
    puts "array($index) = $legacy($index)"
}

# If you have Tcl 8.5 and more, use the below line of code
array set latest [list {*}$content]
  foreach index [array names latest] {
    puts "array($index) = $latest($index)"
}