-1

I have a text file that contains output from a program. It reads like this:

1 2
23 24
54 21
87 12

I need the output to be

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

and so on.

Each line is seperated by a space. How can I parse the lines to the array format as described above, using TCL? (I am doing this for NS2 by the way)

Dinesh
  • 16,014
  • 23
  • 80
  • 122
  • 2
    When you say "using TCL," you mean "using TCL syntax," correct? Otherwise I'm confused why you added the bash and awk tags. – Wintermute Mar 11 '15 at 07:59

3 Answers3

2

With awk:

awk '{ print "arr[" $1 "]=" $2 }' filename
Wintermute
  • 42,983
  • 5
  • 77
  • 80
2

You have mentioned that each line is separated by space, but gave the content separated by new line. I assume, you have each line separated by new line and in each line, the array index and it's value are separated by space.

If your text file contains only those texts given as below

1 2
23 24
54 21
87 12

then, you first read the whole file into a string.

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

Now, with array set we can easily convert them into an array.

# 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)"
}

Suppose if your file has some other contents along with these input contents, then you can get them alone using regexp and you can add elements to the array one by one with the classical approach.

Dinesh
  • 16,014
  • 23
  • 80
  • 122
1

You can use this in BASH:

declare -A arr

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

Testing:

declare -p arr
declare -A arr='([23]="24" [54]="21" [87]="12" [1]="2" )'
anubhava
  • 761,203
  • 64
  • 569
  • 643