0

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?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.