Reputation: 21
i'm using some simulator that uses Tcl for transcript commands (Questa sim) i want to echo file content like "cat" command in unix.
can it be done in one line command at tcl? is it possible to "cat" just the 5 first lines of file
Upvotes: 1
Views: 6595
Reputation: 70
Here is the following code, to read 5 lines at a time from a given file.
#!/usr/bin/tclsh
set prev_count -1
set fp [open "input-file.txt" "r"]
set num_lines [split [read $fp] \n]
for {set i 4} {$i < [llength $num_lines]} { incr i 5} {
set line_5 [lrange $num_lines [incr prev_count] $i ]
set prev_count $i
puts "$line_5\n\n"
}
Upvotes: 0
Reputation: 1043
In one line
puts [read [open data.dat r]]
OR step by step..
set handle [open data.dat r]
puts [read $handle]
close $handle
Upvotes: 4
Reputation: 137567
To open a file and echo its contents to standard output (just like cat
), do this:
set f [open $filename]
fcopy $f stdout
close $f
To just do the first five lines (which is just like head -5
), use this procedure:
proc head {filename {lineCount 5}} {
set f [open $filename]
for {set i 0} {$i < $lineCount} {incr i} {
if {[gets $f line] >= 0} {
puts $line
}
}
close $f
}
It takes more work because it's more complex to detect line endings than it is to just ship bytes around.
Upvotes: 2