0

Is it possible to send the values as stored in variables instead of file2 file1. Kindly let me know how to pass the variables in the above-mentioned query. I tried to pass the variables into the query, but the variables store the value as a single row and I couldn't get the required output.

Thanks for the response. Consider the above-mentioned values in file1 &file2 are command outputs and I stored it in variables, and I want to know-how to pass those variables in this query. Hope this is clear.

[p001 ~]$ cat file1 
30042020
29042020
28042020
27042020
26042020
25042020
24042020

[p001 ~]$ cat file2 
303 30042020
259 29042020
288 28042020
402 27042020
75  26042020
207 25042020

[p9147724_local@dotenprlpbas001 ~]$ var1=$(cat file1) 
[p9147724_local@dotenprlpbas001 ~]$ var2=$(cat file2) 

[p001 ~]$ awk 'NR == FNR{ a[$2] = $1; next } { print $1, a[$1]+0 }' "$var2" "$var1" 
awk: fatal: cannot open file `303 30042020 259 29042020 288 28042020 402 27042020 75 26042020 207 25042020' for reading (No such file or directory) 

expected output:

30042020 303
29042020 259
28042020 288
27042020 402
26042020 75
25042020 207
24042020 0 
αғsнιη
  • 41,407

2 Answers2

3

You just need to change a[$1] = $2 to a[$2] = $1, so:

awk 'NR == FNR{ a[$2] = $1; next }; { print $1, $1 in a?a[$1]: "0" }' file2 file1

However that can be shortened to just:

awk 'NR == FNR{ a[$2] = $1; next } { print $1, a[$1]+0 }' file2 file1

Update: To reading the inputs from output of commands cmdX & cmdY.

awk 'NR == FNR{ a[$2] = $1; next } { print $1, a[$1]+0 }' <(cmdY) <(cmdX)

if the shell you are using doesn't support Process-Substitution: you can do as following:

( cmdY | ( cmdX | (
awk '
    NR == FNR{ a[$2] = $1; next } { print $1, a[$1]+0 }
' /dev/fd/3 /dev/fd/4 ) 4<&0 ) 3<&0 )
αғsнιη
  • 41,407
0

The join util can match the hits, but needs a second pass and printf formatting to match the misses then print a 0:

join -2 2 file{1,2} ; printf '%s 0\n' $(join -v 1 -2 2 file{1,2})

Note: join expects that both files are sorted in the same order.

agc
  • 7,223