Awk comparision

Hi Everyone

I am new to Unix shell scripting

Can anyone please explain me in detail how this command works

 
awk -F@ 'NR==FNR{A[$1]=$2;next}$3 in A{$3=A[$3]}1'  file2 file1

The above command I got it from this forum, but unable to implement it as I am not getting how this works:mad:

I have two files abc.txt and xyz.txt

abc.txt

 
1,2,3,4
5,6,7,8
9,0,1,2
 

xyz.txt
2,1
6,2

2nd column of first file should be compared with 1st column of second file, it match is found, 4th colmn of first file should be updated with the second column of the second file

Output should be

1,2,3,1
5,6,7,2
9,0,1,2
 

Please provide me command and explaination.

Thank you for your help in advance.

awk -F',' 'NR==FNR{A[$1]=$2;next}$2 in A{$4=A[$2]}1' OFS=, file2 file1
2 Likes

Please use code tags. Otherwise, the admins will chase you down. I am a pure biologist, I tried to work on your task using the following commands. But, in awk there is one single liner, to do your task.

Check these commands. Hope they help

$ cat 1
1,2,3,4
5,6,7,8
9,0,1,2
$ cat 2
2,1
6,2
awk -F, '{print $1"\t"$2"\t"$3"\t"$4}' 1 > temp && mv temp 1
awk -F, '{print $1"\t"$2}' 2 > temp && mv temp 2

The above commands will replace comma with tab.

The changed files will look like this.

$ cat 1
1	2	3	4
5	6	7	8
9	0	1	2
$ cat 2
2	1
6	2

Join can be used for your task.

$ join -12 -21 1 2 | awk '{print $2"\t"$1"\t"$3"\t"$5}' > output

Main output file is this

$ cat output
1	2	3	1
5	6	7	2

---------- Post updated at 12:28 PM ---------- Previous update was at 12:27 PM ----------

You were very fast before my lengthy post.

Thanks for the useful command though.

Thank you balaji ..it works :slight_smile: