![使用 awk 如何比较两个字段并打印出一些内容](https://linux22.com/image/144964/%E4%BD%BF%E7%94%A8%20awk%20%E5%A6%82%E4%BD%95%E6%AF%94%E8%BE%83%E4%B8%A4%E4%B8%AA%E5%AD%97%E6%AE%B5%E5%B9%B6%E6%89%93%E5%8D%B0%E5%87%BA%E4%B8%80%E4%BA%9B%E5%86%85%E5%AE%B9.png)
假设我有file1
以下内容:
1,2,3,4,12,6
1,2,3,5,333,6
1,2,3,12,5,6
1,2,3,44,101,6
同时file2
有以下内容:
22,4,111,1,6,7,12
22,4,56,55,6,7,12
22,4,12,12,6,7,12
22,4,333,102,6,7,12
我想要的是如果5th
字段的file1
值大于打印3rd
字段的值file2
,例如Value 333 greater than 56
如何使用 awk 来完成此操作?
答案1
$ awk -F, 'FILENAME=="file1" {inputs[FNR]=$5} FILENAME=="file2" && inputs[FNR] > $3 {print inputs[FNR] " is greater than " $3 " on line " FNR}' file1 file2
333 is greater than 56 on line 2
答案2
我使用下面的方法来获得相同的所需输出
for i in {1..4}; do second_file=`awk -F "," -v i="$i" 'NR==i{print $3}' j.txt`; first_file=`awk -F "," -v i="$i" 'NR==i {print $5}' l.txt`; if [[ $first_file -gt $second_file ]]; then echo $first_file is greater than $second_file; fi; done
输出
333 is greater than 56