gpt4 book ai didi

linux - 如何使用awk检查文本文件中的行是否存在于另一个文本文件中

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:28:46 28 4
gpt4 key购买 nike

这是后续问题:Unexpected result comparing values of rows and columns in two text files

我创建了一个结构来根据行和列比较两个文本文件。以下是文件结构:

文件1.txt

Name  Col1  Col2  Col3 
-----------------------
row1 1 4 7
row2 2 5 8
row3 3 6 9

文件2.txt

Name  Col1  Col2  Col3   
-----------------------
row1 1 4 7
row2 2 5 999

这是我目前的代码:

dos2unix ravi   # 2>/dev/null
dos2unix ravi2 # 2>/dev/null

awk '
FNR < 2 {next} # skips first two lines
FNR == NR {
for (i = 2; i <= NF; i++) {
a[i,$1] = $i;
}
b[$1];
next;
}

($1 in b) { # check if row in file2 existed in file1
for (i = 2; i <= NF; i++) {
if (a[i,$1] == $i)
printf("%s->col%d: %s vs %s: Are Equal\n", $1, i-1, a[i,$1], $i);
else
printf("%s->col%d: %s vs %s: Not Equal\n", $1, i-1, a[i,$1], $i);
}
}

!($1 in b) { # check if row in file2 doesn't exist in file1.
for (i = 2; i <= NF; i++)
printf("%s->col%d: %s vs %s: Are Not Equal\n", $1, i-1, "blank", $i);
}

// pattern needed to check if row in file1 doesn't exist in file2.

' $PWD/file1.txt $PWD/file2.txt

有没有人有任何提示、建议或提示在 awk 语句中有一个模式来检查 file1 中的行是否不存在于 file2 中。请参阅下面的示例输出以了解我的意思。 (即:基本上,我想打印 file1 中 row3 的值在 file2 中不存在)。谢谢!如果需要进一步解释,请告诉我。

期望的输出:

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
row3->Col1: 3 vs (blank) : Not Equal
row3->Col2: 6 vs (blank) : Not Equal
row3->Col3: 9 vs (blank) : Not Equal

实际输出:

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

最佳答案

扩展你的答案:

$ cat script.awk 
FNR < 2 { next } # skips first two lines
FNR == NR {
for (i = 2; i <= NF; i++) { a[i,$1] = $i }
b[$1];
next;
}
($1 in b) { # check if row in file2 existed in file1
for (i = 2; i <= NF; i++) {
if (a[i,$1] == $i)
printf("%s->col%d: %s vs %s: Are Equal\n", $1, i-1, a[i,$1], $i);
else
printf("%s->col%d: %s vs %s: Not Equal\n", $1, i-1, a[i,$1], $i);
}
delete b[$1]; # delete entries which are processed
}

END {
for (left in b) { # look which didn't match
for (i = 2; i <= NF; i++)
printf("%s->col%d: %s vs (blank): Not Equal\n", left, i-1, a[i,left])
}
}

像这样运行它:

$ awk -f script.awk file1 file2
row1->col1: 1 vs 1: Are Equal
row1->col2: 4 vs 4: Are Equal
row1->col3: 7 vs 7: Are Equal
row2->col1: 2 vs 2: Are Equal
row2->col2: 5 vs 5: Are Equal
row2->col3: 8 vs 999: Not Equal
row3->col1: 3 vs (blank): Not Equal
row3->col2: 6 vs (blank): Not Equal
row3->col3: 9 vs (blank): Not Equal

关于linux - 如何使用awk检查文本文件中的行是否存在于另一个文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24331533/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com