使用TCL比较2个文件之间的列

时间:2018-03-27 11:38:45

标签: tcl

我有2个只有一列的文件。说file1.txt和file2.txt。 以下是文件内的内容 在file1.txt里面

Tom
Harry
Snowy
Edward

在file2.txt内部

Harry
Tom
Edward

2)我想编写一个代码,用于检查列中的每个项目并打印如下内容。

"Tom, Harry, Edward" are present in both the files
Snowy is there in file1.txt but not in file2.txt

3)基本代码

    set a [open file1.txt r]
set b [open file2.txt r]
while {[gets $a line1] >= 0 && [gets $b line2] >= 0} {
    foreach a_line $line1 {
        foreach b_line $line2 {
            if {$a_line == $b_line } {
            puts "$a_line in file test1 is present in $b_line in file test2\n"
            } else {
            puts "$a_line is not there\n"
            }
        }
    }
}
close $a
close $b

问题是它没有检查列中的每个名称。 任何建议。

提前致谢。 尼尔

1 个答案:

答案 0 :(得分:1)

您要做的是分别读取每个文件而不是嵌套循环:

# read the contents of file1 into an associative array
# store the user as an array **key** for fast lookoup
set fh [open "file1.txt" r]
while {[gets $fh user] != -1} {
    set f1tmp($user) ""
}
close $fh

# read file2 and compare against file1
array set users {both {} file1 {} file2 {}}
set fh [open "file2.txt" r]
while {[gets $fh user] != -1} {
    if {[info exists f1tmp($user)]} {
        lappend users(both) $user
        unset f1tmp($user)
    } else {
        lappend users(file2) $user
    }
}
close $fh

set users(file1) [array names f1tmp]
parray users
users(both)  = Harry Tom Edward
users(file1) = Snowy
users(file2) = 

或者正如Donal建议的那样,使用tcllib

package require struct::set

set fh [open file1.txt r]
set f1users [split [read -nonewline $fh] \n]
close $fh

set fh [open file2.txt r]
set f2users [split [read -nonewline $fh] \n]
close $fh

set results [struct::set intersect3 $f1users $f2users]
puts "in both: [join [lindex $results 0] ,]"
puts "f1 only: [join [lindex $results 1] ,]"
puts "f2 only: [join [lindex $results 2] ,]"
in both: Harry,Tom,Edward
f1 only: Snowy
f2 only: