简体   繁体   English

使用 awk 命令将 2 个文件与算术进行比较

[英]compare 2 files with arithmetic using awk command

I have 2 files:我有2个文件:

File 1文件 1

*Name|Date|id|Total*
Jimmy|03-OCT-18|BST100114262|20000
Dedi|03-OCT-18|BST100904288|10000

File 2档案 2

*Name|Amount*
Anton|9800
Jimmy|90000

Output : Jimmy|20000|90000|1800000000输出:吉米|20000|90000|1800000000

I've tried, but no luck.我试过了,但没有运气。

awk -F'|' 'NR==FNR{a[$1]=$1; next} (($1 in a) && (a[$4] >= $2 )) { print a[$4]*$2 }'

Could you please try following. 您可以尝试以下吗?

awk -F'|' 'NR==FNR{a[$1]=$4; next} (($1 in a) && (a[$1] <= $2 )) {$(NF+1)=a[$1]*$2;$2=a[$1] OFS $2;print}'  OFS="|" File1 File2

Output will be as follows. 输出如下。

Jimmy|20000|90000|1800000000

Another: 另一个:

$ awk 'BEGIN{FS=OFS="|"}($1 in a)&&FNR>1{print $1,a[$1],$NF,a[$1]* $NF}{a[$1]=$NF}' file1 file2

outputs: 输出:

Jimmy|20000|90000|1800000000

Explained some using Jimmies: 使用Jimmies进行了一些解释:

$ awk '
BEGIN { FS=OFS="|" }               # set separators
($1 in a) && FNR>1 {               # if key to hash (Jimmy) is in a excluding headers
    print $1,a[$1],$NF,a[$1]* $NF  # process Jimmy
    # next                         # this excludes new Jimmy from being rehashed to a
}
{
    a[$1]=$NF                      # ... in here where everything is hashed and  the
}' file1 file2                     # ... existing rehashed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM