忽略文件 TCL 中的行
Ignoring lines in a file TCL
假设我有一个 file1,里面有一些查询,
Query 1
Query 2
Query 3
我有一个包含一堆数据的普通文本文件 2
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
如何创建一个循环,使其忽略包含来自 file1 的查询的行并仅打印文件中没有查询的行?所以在这种情况下,只有这些值被打印
Data1 continue no query
Data2 continue no query
我尝试使用我制作的这个循环脚本生成结果
将要忽略的查询从 file1 存储到 $wlistItems
set openFile1 [open file1.txt r]
while {[gets openFile1 data] > -1} {
set wlist $data
append wlistItems "{$wlist}\n"
}
close $openFile1
正在处理文件 2 以打印没有忽略查询的行
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
但是,脚本不会跳过这些行。它而是打印出 file2 中的重复数据。
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
}
}
更简单的解决方案:
package require fileutil
set queries [join [split [string trim [::fileutil::cat file1]] \n] |]
::fileutil::foreachLine line file2 {
if {![regexp ($queries) $line]} {
puts $line
}
}
第一个命令(在 package require
之后)读取包含查询的文件并将它们打包为一组分支 (Query 1|Query 2|Query 3
)。第二个命令逐行处理第二个文件并打印那些不包含任何这些分支的行。
文档:fileutil package, if, join, package, puts, Syntax of Tcl regular expressions, regexp, set, split, string
我会这样做:
puts [exec grep -Fvf file1 file2]
假设我有一个 file1,里面有一些查询,
Query 1
Query 2
Query 3
我有一个包含一堆数据的普通文本文件 2
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
如何创建一个循环,使其忽略包含来自 file1 的查询的行并仅打印文件中没有查询的行?所以在这种情况下,只有这些值被打印
Data1 continue no query
Data2 continue no query
我尝试使用我制作的这个循环脚本生成结果
将要忽略的查询从 file1 存储到 $wlistItems
set openFile1 [open file1.txt r]
while {[gets openFile1 data] > -1} {
set wlist $data
append wlistItems "{$wlist}\n"
}
close $openFile1
正在处理文件 2 以打印没有忽略查询的行
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
但是,脚本不会跳过这些行。它而是打印出 file2 中的重复数据。
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
}
}
更简单的解决方案:
package require fileutil
set queries [join [split [string trim [::fileutil::cat file1]] \n] |]
::fileutil::foreachLine line file2 {
if {![regexp ($queries) $line]} {
puts $line
}
}
第一个命令(在 package require
之后)读取包含查询的文件并将它们打包为一组分支 (Query 1|Query 2|Query 3
)。第二个命令逐行处理第二个文件并打印那些不包含任何这些分支的行。
文档:fileutil package, if, join, package, puts, Syntax of Tcl regular expressions, regexp, set, split, string
我会这样做:
puts [exec grep -Fvf file1 file2]