使用 TCL 比较 2 个文件之间的列 [英] Compare columns between 2 files using TCL

查看:21
本文介绍了使用 TCL 比较 2 个文件之间的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 files having only one column. Say file1.txt and file2.txt. Below are the contents inside the file Inside file1.txt

Tom
Harry
Snowy
Edward

在 file2.txt 内

Inside file2.txt

Harry
Tom
Edward

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

2) I want to write a code that will check each item in the column and print something as below.

"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

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

Issue is that it is not checking each name in the column. Any suggestions.

提前致谢.尼尔

推荐答案

你想要做的是分别读取每个文件并且没有嵌套循环:

What you want to do is read each file separately and not have nested loops:

# 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

Or as Donal suggests, use 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:

这篇关于使用 TCL 比较 2 个文件之间的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆