awk 文件比较

Awk file compare

两个文件,组件名称和版本号由 space:

分隔
cat file1
com.acc.invm:FNS_PROD 94.0.5
com.acc.invm:FNS_TEST_DCCC_Mangment 94.1.6
com.acc.invm:FNS_APIPlat_BDMap 100.0.9
com.acc.invm:SendEmail 29.6.113
com.acc.invm:SendSms 12.23.65
com.acc.invm:newSer 10.10.10

cat file2 
com.acc.invm:FNS_PROD 94.0.5
com.acc.invm:FNS_TEST_DCCC_Mangment 94.0.6
com.acc.invm:FNS_APIPlat_BDMap 100.0.10
com.acc.invm:SendEmail 29.60.113
com.acc.invm:SendSms 133.28.65
com.acc.invm:distri_cob 110.10.10

需要的输出是:

(1) 来自 file1 的组件列表,这些组件在 file1 中但不存在于 file2 中。
(2) 来自 file2 的组件列表,这些组件在 file1 中但不存在于 file2 中。

在此示例中,所需的输出是:

来自文件 1 的组件:

com.acc.invm:newSer 10.10.10

来自文件 2 的组件:

com.acc.invm:distri_cob 110.10.10

注意:如果组件存在不同版本,我们必须忽略。

我的代码是: (1)

 cat new.awk
 { split(,a,/\./); curr = a[1]*10000 + a[2]*100 + a[3] }
 NR==FNR { prev[] = curr; next }
 !( in prev) && (curr > prev[])

 /usr/bin/nawk -f new.awk f2 f1

输出

com.acc.invm:newSer 10.10.10

(2)

/usr/bin/nawk -f new.awk f1 f2

输出

com.acc.invm:distri_cob 110.10.10

这个逻辑对吗?和

任何人都可以帮助我如何在我的脚本本身中编写 new.awk 所以 new.awk 文件不应该是 运行 所必需的。

我可以建议一个简单的单行代码做同样的事情但是 w/o awk 编程吗?

cat file2 file1 file2|cut -f 1 -d" "|sort|uniq -u| xargs -I'{}' grep '{}' file1
com.acc.invm:newSer 10.10.10


cat file1 file2 file1|cut -f 1 -d" "|sort|uniq -u| xargs -I'{}' grep '{}' file2
com.acc.invm:distri_cob 110.10.10

您可以通过单次调用 awk 来打印两个文件中的独特组件:

# Save all the components from the first file into an array
NR == FNR { a[] = [=10=]; next }

# If a component from the second file is found, delete it from the array
 in a { delete a[]; next }

# If a component in the second file is not found, print it
{ print }

# Print all the components from the first file that weren't in the second
END { for (i in a) print a[i] }


$ cat file1
com.acc.invm:FNS_PROD 94.0.5
com.acc.invm:FNS_TEST_DCCC_Mangment 94.1.6
com.acc.invm:FNS_APIPlat_BDMap 100.0.9
com.acc.invm:SendEmail 29.6.113
com.acc.invm:SendSms 12.23.65
com.acc.invm:newSer 10.10.10


$ cat file2
com.acc.invm:FNS_PROD 94.0.5
com.acc.invm:FNS_TEST_DCCC_Mangment 94.0.6
com.acc.invm:FNS_APIPlat_BDMap 100.0.10
com.acc.invm:SendEmail 29.60.113
com.acc.invm:SendSms 133.28.65
com.acc.invm:distri_cob 110.10.10


$ awk -f cf.awk file2 file1
com.acc.invm:newSer 10.10.10
com.acc.invm:distri_cob 110.10.10

对于你问题的第二部分,如果你想 运行 这没有单独的 awk 文件中的代码,你可以像这样内联代码:

 awk 'NR==FNR {a[]=[=11=]; next}  in a {delete a[]; next}1 END {for (i in a) print a[i]}' file2 file1

(请注意,END 之前的 1{ print } 相同,因为 1 始终为真,而 print 是默认值行动。)

如果您只需要组件名称(不带版本)

$ p() { cut -d' ' -f1  | sort; }; comm -23 <(p file1) <(p file2)
com.acc.invm:newSer

$ p() { cut -d' ' -f1  | sort; }; comm -13 <(p file1) <(p file2)
com.acc.invm:distri_cob

如果你需要版本号,你可以管道到

 ... | xargs -I{} grep {} file2

与 file1 类似,如@LiMar 的解决方案