Reputation: 65
I have 2 files 1.txt and 2.txt
1.txt contains below details
user = 10
user2 = 20
user3 = 30
2.txt contains below details
user = 25MB
user2 = 30MB
I need to compare both the files if the string matches in the files it should append the data from 1st file and if it does not match it should append 0 in shell script
Desired output
user = 10 25MB
user2 = 20 30MB
user3 = 30 0MB
I am using the command:
awk 'FNR==NR{a[$1$2];next}!($1$2 in a)' 1.txt 2.txt
but not getting the desired output. I am new to shell scripting and looking for full implementation help.
Could you please help me with the syntax and implementation?
Upvotes: 0
Views: 74
Reputation: 74615
You could use something like this:
$ awk 'NR == FNR { a[$1] = $3; next }
{ printf "%s = %s %s\n", $1, $3, ($1 in a ? a[$1] : "0MB") }' 2.txt 1.txt
user = 10 25MB
user2 = 20 30MB
user3 = 30 0MB
I chose to read the files in the opposite order, 2.txt
, then 1.txt
. The keys and values from 2.txt
are stored in the array a
. For each line in 1.txt
, the value in the array corresponding to the key is used if present.
Upvotes: 1