Pick out certain lines from files

85 views Asked by At

I am writing a tcl script that reads from a file and displays certain lines from this file. I can read from the file n problem but I cant figure out how to pick out certain lines BEFORE filtering out what I don't need. I am reading the file to a list and then using the following code to filter it out;

proc listFromFile {/.../.../.../file_test.file} {
set f [open /.../.../.../file_test.file r]
set data [split [string trim [read $f]]]
close $f
return $data
}
set f [listFromFile /.../.../.../file_test.file]
set f [lsort -unique $f]
set f [lsearch -all -inline $f "test_*"

The lines within the file look like

$(eval $(call CreateUvmTest, other, test_runtest1 ...
$(eval $(call CreateUvmTest, KEYWORD, test_runtest2 ...
$(eval $(call CreateUvmTest, KEYWORD, test_runtest3 ...
$(eval $(call CreateUvmTest, other, test_runtest4 ...

How would I pick out the lines containing KEYWORD as a whole before I filter out everything else I don't need? The lines containing KEYWORD are randomly within the file along with other tests. Is this a possibility at all?

2

There are 2 answers

3
Peter Lewerin On BEST ANSWER

It shouldn't be hard. To begin with, you probably want to split the file's contents at the line breaks:

set data [split [string trim [read $f]] \n]

When you've done that, you could use a number of techniques to select the lines you want, for instance

lsearch -all -inline $data *KEYWORD*

Documentation: lsearch, read, set, split, string

0
glenn jackman On

I would strongly consider

set lines [split [exec grep -Fw KEYWORD file_test.file] \n]

Otherwise

proc select_lines {filename keyword} {
    set fid [open $filename r]
    while {[gets $fid line] != -1} {
        if {[string match "*$keyword*" $line]} {lappend lines $line}
    }
    close $fid
    return $lines
}
set lines [select_lines file_test.file KEYWORD]