Reputation: 1
tcl
I wanna compare two files line by line.
file1
file2
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
please help me thank you
Upvotes: 0
Views: 479
Reputation: 246877
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}
Upvotes: 0
Reputation:
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
Upvotes: 0