拆分线由空格分隔到数组

时间:2015-03-11 07:17:46

标签: tcl ns2

我有一个包含程序输出的文本文件。它读起来像这样:

1 2
23 24
54 21
87 12

我需要输出

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

等等。

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

3 个答案:

答案 0 :(得分:2)

使用awk:

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

答案 1 :(得分:2)

您已经提到每行都用空格分隔,但是内容用新行分隔。我假设,每条线都用新线分隔,在每一行中,数组索引和它的值用空格分隔。

如果您的文字文件仅包含以下提供的文字

1 2
23 24
54 21
87 12

然后,您首先将整个文件读成字符串。

set fp [open "input.txt" r]
set content [ read $fp ]
close $fp

现在,使用array set,我们可以轻松地将它们转换为数组。

# 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单独使用它们,并且可以使用经典方法逐个添加元素。

答案 2 :(得分:1)

你可以在BASH中使用它:

declare -A arr

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

<强>测试

declare -p arr
declare -A arr='([23]="24" [54]="21" [87]="12" [1]="2" )'
相关问题