Comparing files and copying differences
I've got 2 files - File1 and File2
File1: abc:123 def:456 tex:765 File2: abc:567 What I would like to do is compare the first column (up to the : ) in the files and write the changes to File2 In other words check abc in File1 against File2, is it exists in File2 then skip, otherwise append it to the file, then check def, then tex etc etc So once the script has run File2 would contain: abc:567 def:456 tex:765 Any ideas - I've played around with awk and for loops but don't seem to be getting anywhere :( |
I don't have complete solution for you but I suggest,
by using uniq command I have found, (for your given example) uniq file1 file2 after that content of file2 abc:123 def:456 tex:765 I think you want 567 in place of 123. "comm" command may be helpful for you. Thanks Kapil Singh |
You might be onto something but the problem is with uniq and comm is that it will compare the whole line.
I only want to compare the first field - semicolon delimited. Update: After many hours of searching I came across this post which does the job!!! :) http://www.unix.com/shell-programmin...n-2-files.html |
maybe by using temporary files filled with the gawk command?
|
Quote:
Code:
sort -t: -msuk1,1 File2 File1 To update File2, don't directly redirect output, because that would truncate File2 before sort reads it. Rather, Code:
sort -t: -msuk1,1 File2 File1 > tmp More robustly and flexibly than the above "sort" call, you could use Perl to build up the hash %t, then write it all out at the end. Note the opposite order of arguments: Code:
perl -we 'while(<>) {($k,$v)=split /:/, $_, 2; $t{$k}=$v;} while (@e = each %t) {print join ":", @e}' File1 File2 Code:
perl -we 'while(<>) {($key,$value)=split /:/, $_, 2; $hash{$key}=$value;} for (sort keys %hash) {print $_, ":", $hash{$_}};' File1 File2 Quote:
Quote:
You can tell uniq to only heed the first 3 characters on each line. That could do in the example, but it's not really colon-delimited. /Christian |
Thanks for the reply.
I should have specified - The keys are in a random order Quote:
Quote:
I ended up using this: Code:
awk -F ":" 'BEGIN{while(getline<"/tmp/file1") a [$1]=1 } ; a [$1] !=1 {print $0 } ' /tmp/file2 > /tmp/file.diff |
How about
Quote:
|
Quote:
Or use one of the Perl one-liners. Quote:
|
All times are GMT -5. The time now is 12:14 PM. |