James
James

Reputation: 125

Ignoring lines in a file TCL

Suppose I have a file1 with a few queries inside,

Query 1
Query 2
Query 3

And I have a normal text file2 containing a bunch of data

Data 1 Query 1 something something
Data something Query 2 something something
Something Query 3 something something
Data1 continue no query
Data2 continue no query

How do I create a loop such that it ignores the lines containing queries from file1 and prints only lines without the queries in the file? so in this case only these values gets printed

Data1 continue no query
Data2 continue no query

i tried producing the results using this loop script i made

Storing the queries to be ignored from file1 into $wlistItems

set openFile1 [open file1.txt r]
while {[gets openFile1 data] > -1} {
set wlist $data
append wlistItems "{$wlist}\n"
}
close $openFile1

Processing file2 to print lines without ignored queries

set openFile2 [open file2.txt r]
while {[gets $openFile2 data] > -1} {
for {set n 0} {$n < [llength $wListItems]} {incr n} {
if {[regexp -all "[lindex $wListItems $n]" $data all value]} {
continue
}
puts $data
}
}
close $openFile2

However, the script does not skip the lines. It instead prints out repeated data from file2.

Upvotes: 2

Views: 2055

Answers (3)

glenn jackman
glenn jackman

Reputation: 246744

I'd just do this:

puts [exec grep -Fvf file1 file2]

Upvotes: 1

Peter Lewerin
Peter Lewerin

Reputation: 13252

A simpler solution:

package require fileutil

set queries [join [split [string trim [::fileutil::cat file1]] \n] |]
::fileutil::foreachLine line file2 {
    if {![regexp ($queries) $line]} {
        puts $line
    }
}

The first command (after the package require) reads the file with the queries and packs them up as a set of branches (Query 1|Query 2|Query 3). The second command processes the second file line by line and prints those lines that don't contain any of those branches.

Documentation: fileutil package, if, join, package, puts, Syntax of Tcl regular expressions, regexp, set, split, string

Upvotes: 1

Dinesh
Dinesh

Reputation: 16428

while {[gets $openFile2 data] > -1} {
    set found 0
    for {set n 0} {$n < [llength $wListItems]} {incr n} {
        if {[regexp -all "[lindex $wListItems $n]" $data all value]} {
            set found 1
            break
        }
    }
    if {!$found} {
        puts $data
     }
}

Upvotes: 2

Related Questions