简体   繁体   中英

compare 2 files with arithmetic using awk command

I have 2 files:

File 1

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

File 2

*Name|Amount*
Anton|9800
Jimmy|90000

Output : Jimmy|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:

$ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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