Updated 2018-01-09 21:17:36 by CecilWesterhof

Created by CecilWesterhof.

I often need a certain line from a file. (Mostly the first.) Because of that I wrote the following two proc's:
proc getLine {fileName {no 1}} {
    if {${no} < 1} {
        error "The linenumber cannot be lower as 1"
    }
    set linesToGo ${no}
    set fd   [open ${fileName} RDONLY]
    while {${linesToGo}} {
        if {-1 == [gets ${fd} line]} {
            error "Line ${no} does not exist for ${fileName}"
        }
        incr linesToGo -1
    }
    close ${fd}
    return ${line}
}

proc getLineAsList {fileName {no 1}} {
    regexp -inline -all {\S+} [getLine ${fileName} ${no}]
}

The first just gets the line and returns it as a string.

Sometimes you need it as a list. For this I wrote the second one that uses the first.

As always: comments, tips and questions are appreciated.

KPV if the file is small, you can just do:
proc GetLineAt {fname lineno} {
    set fin [open $fname r]
    set lines [split [read $fin] \n]
    close $fin

    return [lindex $lines $lineno-1]
}

CecilWesterhof I want it to be as generic as possible and in most cases I need the first line. But thanks for the tip.


[Category Utilities]