2

I have two different files with two columns each.

file1.txt

DevId   Group
aaa     A
bbb     B

file2.txt

Group   RefId
A       111-222-333
B       444-555-666

I need only need DevId and its corresponding RefId.

Required Output

DevId   RefId
aaa     111-222-333
bbb     444-555-666

I tried using this syntax but I can't get it correctly.

awk -F, -v OFS=, 'NR==FNR{a[$1]=$2;next}{print a[$2],$1}' file2.txt file1.txt

I hope someone could help me.

Inian
  • 80,270
  • 14
  • 142
  • 161
jecha
  • 33
  • 2

1 Answers1

2

Here:

awk -v RS="\r\n" 'FNR==NR{a[$1]=$2;next}{ print $1, a[$2]}' file2.txt file1.txt

This was modified from Awk multiple files which I suggest you read for the explanation.

Edit: As mentioned by @JamesBrown, added -v RS="\r\n" for line endings

ssemilla
  • 3,900
  • 12
  • 28
  • I tried this. But I can only get DevId. I'll read that. Thanks! – jecha Nov 10 '18 at 06:51
  • What do you mean you "can only get DevId"? I've tried this in my local machine and it outputs your required output. – ssemilla Nov 10 '18 at 06:59
  • The output are only values under DevId. – jecha Nov 10 '18 at 07:11
  • 3
    OP, you have `\r\n` line endings. Use `awk -v RS="\r\n" ...` The same fixes @RavinderSingh13's answer as well. – James Brown Nov 10 '18 at 07:15
  • @jecha, I updated the answer thanks to @JamesBrown. I would also suggest using `dos2unix` when working with files in in Linux if you can since most of unix tools are expecting unix line endings. – ssemilla Nov 10 '18 at 07:21
  • Thank you also ssemilla for the command. Great help. I added what James Brown said and it worked. – jecha Nov 10 '18 at 07:23
  • If you are satisfied with the answer, you should mark it as accepted so that questions will not be in the "Unanswered" list. – ssemilla Nov 10 '18 at 07:29