Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting text file and adding table header...

Status
Not open for further replies.

ee1

Programmer
May 31, 2011
25
IL
Hi all,
I am new to tcl and have a question..
I have the followwing txt file:

| text1 | 34.540000 5.1800000 | 0.281900 |
| text2 | 69.230000 7.9100000 | 0.022220 |

and continue...
my question is:
i would like to:
1. sort the file by the second column..
2. i would like to add the file a header, somting like:
+-------+-----------------+---------+
| Name | Number1 Number2 | Number3 |
+-------+-----------------+---------+
3. how can i show the numbers in the second column only 2 digits after the numberical dot?


thanks alot!
 
Read the file into a list:
Code:
set fid [open <text file name> r]
set lst_lines [split [read $fid] \n]
close $fid
set lst2_lines ""
foreach line $lst_lines {
   lappend lst2_lines [split $line " "]
}
now "lst2_lines" should be a list, each element of which is a list, each element of which is a column. Now, to sort, you will use the "-index" option of the list sort function, "lsort"
-index index
If this option is specified, each of the elements of list must itself be a proper Tcl sublist. Instead of sorting based on whole sublists, lsort will extract the index'th element from each sublist and sort based on the given element. The keyword end is allowed for the index to sort on the last sublist element, and end-index sorts on a sublist element offset from the end. For example,
lsort -integer -index 1 {{First 24} {Second 18} {Third 30}}

returns {Second 18} {First 24} {Third 30}, and

lsort -index end-1 {{a 1 e i} {b 2 3 f g} {c 4 5 6 d h}}

returns {c 4 5 6 d h} {a 1 e i} {b 2 3 f g}. This option is much more efficient than using -command to achieve the same effect.
Code:
set lst2_lines [lsort -index 1 $lst2_lines]
Now you'll write the new list to a file but before you do, you'll write the header
Code:
set fid [open <text file name> w]
puts $fid [join {text1 text2 text3...} \t]
foreach lstelem $lst2_lines {
   puts $fid [join $lstelem \t]
}
close $fid

_________________
Bob Rashkin
 
first of all - thanks for the detailed answer!
secondly,
any idea why when trying to source this script i am getting:
"set: Variable name must begin with a letter."

thanks!
 
you may have mistaken my "lst..." (starts with lower case L) for "1st..." (starts with the digit, one).

_________________
Bob Rashkin
 
nop... :-\
all my variable starts with a letter...
 
without seeing your code, it's hard to say.

_________________
Bob Rashkin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top