how to compare lines of two files and change the matched line in one file in tcl

316 Views Asked by At

tcl

I wanna compare two files line by line.

file1

  1. abc
  2. 123
  3. a1b2c3

file2

  1. abc

  2. 00 a1b2c3

if the line of file1 matched one of the line of file2, change the line of file1 to the line of file2

so the output file woule be like that.

file1

  1. abc

  2. 123
  3. 00 a1b1c3

please help me thank you

2

There are 2 best solutions below

0
On

Here's a working example, if necessary adjust file paths to fit your needs.

This code makes a temporary work file that overwrites the original file1 at end.

set file1Fp [open file1 "r"]
set file1Data [read $file1Fp]
close $file1Fp

set file2Fp [open file2 "r"]
set file2Data [read $file2Fp]
close $file2Fp

set tempFp [open tempfile "w"]

foreach lineFile1 [split $file1Data "\n"] {
    set foundFlag 0
    foreach lineFile2 [split $file2Data "\n"] {
        if { $lineFile1 == {} } continue
        if { [string match "*$lineFile1*" $lineFile2] } {
            set foundFlag 1
            puts $tempFp "$lineFile2"
        }
    }
    if { $foundFlag == 0 } {
        puts $tempFp "$lineFile1"
    }
}

close $tempFp

file rename -force tempfile file1
0
On

You could write

set fh [open file2]
set f2_lines [split [read -nonewline $fh] \n]
close $fh

set out_fh [file tempfile tmp]
set fh [open file1]
while {[gets $fh line] != -1} {
    foreach f2_line $f2_lines {
        if {[regexp $line $f2_line]} {
            set line $f2_line
            break
        }
    }
    puts $out_fh $line
}
close $fh
close $out_fh

file rename -force $tmp file1

Depending on how you want to compare the two lines, the regexp command can also be expressed as

  • if {[string match "*$line*" $f2_line]}
  • if {[string first $line $f2_line] != -1}