1

Hi I have two files containing data: file1:

4,abc
3,xyz
5,fut
6,gfd

file2:

gfd,2.3
xyz,4.5
abc,6.7
fut,3.2

i wish to create a file3 as output file using linux scripting commands:

4,6.7
3,4.5
5,3.2
6,2.3

how do I use FR=NFR etc. awk scripting to do this

1

With join:

join -t, -1 2 -2 1 -o 1.1,2.2 <(sort -t, -k2 file1) <(sort -t, -k1 file2)
  • -t, set delimiter to ,.
  • -1 2 the first files join field is the second one.
  • -2 1 the second files join field is the first one.
  • -o 1.1,2.2 the output format
  • <(sort ...) join need input files, which are sorted on the join field.
0

With awk:

script.awk:

FNR==NR{
    var[$2]=$1
}
FNR!=NR{
    print(var[$1]","$2)
}

Call the script with

awk -F, -f script.awk file1 file2
0

Similar awk one liner:

awk -F"," 'FNR==NR{var[$2]=$1;next;}{print var[$1]FS$2}'  file1 file2

Output:

$ awk -F"," 'FNR==NR{var[$2]=$1;next;}{print var[$1]FS$2}'  file1.txt file2.txt
6,2.3
3,4.5
4,6.7
5,3.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.