问题
This is related to one of my previous question: How to compare values of rows and columns of two text files in bash?
file1.txt (with special characters: cat -vet file1.txt)
Name Col1 Col2 Col3^M$
-----------------------^M$
row1 1 4 7^M$
row2 2 5 8^M$
row3 3 6 9$
file2.txt (with special characters: cat -vet file2.txt)
Name Col1 Col2 Col3^M$
-----------------------^M$
row1 1 4 7^M$
row2 2 5 999$
I have somewhat figured out a way to compare two files. But for some reason it is not giving me the result that I want. Here is the code I use to compare the files.
awk '
FNR < 2 { next }
FNR == NR {
for (i = 2; i <= NF; i++)
{
a[i,$1] = $i;
}
b[$1];
next;
}
($1 in b) {
for (i = 2; i <= NF; i++)
{
if (a[i,$1] == $i)
printf("%s->Col%d: %d vs %d: Equal\n", $1, i-1, a[i,$1], $i);
else
printf("%s->Col%d: %d vs %d: Not Equal\n", $1, i-1, a[i,$1], $i);
}
} ' file1.txt file2.txt
Expected result:
row2->Col1: 1 vs 1: Equal
row2->Col2: 4 vs 4: Equal
row2->Col3: 7 vs 7: Equal
row1->Col1: 2 vs 2: Equal
row1->Col2: 5 vs 5: Equal
row1->Col3: 8 vs 999: Not Equal
Actual result:
row2->Col1: 1 vs 1: Equal
row2->Col2: 4 vs 4: Equal
row2->Col3: 0 vs 7: Not Equal
row1->Col1: 2 vs 2: Equal
row1->Col2: 5 vs 5: Equal
row1->Col3: 0 vs 999: Not Equal
Does anyone know why lines 3 and 6 of the actual result are comparing with 0 (not supposed to do so)?
回答1:
Special thanks to @jaypal for helping me solve the problem. The problem was that these text files were created in MS-DOS and had to be converted to Unix format in order to be executed in Linux or Unix environment. So before executing the segment of code from the question above, I had to use this command: dos2unix file1.txt
来源:https://stackoverflow.com/questions/24316140/unexpected-result-comparing-values-of-rows-and-columns-in-two-text-files