我有两个文件要比较:
- 与“temp”文件进行比较后,我从“base”文件中获取第二列中的值
- 不断变化的“temp”文件(例如,在每个循环中)
“基础”文件:
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
“临时”文件:
2.3
1.8
4.5
为了进行比较,使用以下代码:
awk 'NR==FNR{A[$1]=$2;next} {i=int($1+.01)} i in A {print A[i]}' base temp
因此,它输出:
b
a
d
正如注意到的,即使“temp”文件中有小数,也会找到并打印相应的字母。但是,我发现,对于较大的文件(例如,“临时”文件中的行记录超过数千行),代码始终输出的“158”行少于“临时”文件中的实际行数。我不明白为什么会发生这种情况,并希望您的支持来避免这种情况。
在以下示例中,“tmpctd”是基本文件,“tmpsf”是更改文件。
awk 'NR==FNR{A[$1]=$2;next} {i=int($1+.01)} i in A {print A[i]}' tmpctd tmpsf
上述比较产生 22623 行,但“tmpsf”(即“temp”文件)有 22781 行。因此,比较两个文件后,减少了 158 行。如需测试,请在此处找到这些文件:https://file.io/pxi24ZtPt0kD和 https://file.io/tHgdI3dkbKhr .
欢迎任何提示。
PS。我更新了两个链接,对此表示抱歉。最佳答案
您能否尝试按照 GNU awk
中所示的示例进行编写和测试。
awk '
FNR==NR{
a[int($1)]
next
}
($1 in a){
print $2
}
' temp_file base_file
说明:为上述内容添加详细说明。
awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition if FNR==NR which will be TRUE when temp_file is being read.
a[int($1)] ##Creating array a which has index as integer value of 1st field of current line.
next ##next will skip all further statements from here.
}
($1 in a){ ##Checking condition if first field is present in array a then do following.
print $2 ##Printing 2nd field of currnet line.
}
' temp_file base_file ##Mentioning Input_file names here.
关于linux - 比较两个文件后的行数少于预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63975887/