0

Main file:

A B
C D
D A
G H

Ref file:

1 A
2 B
3 C
4 D
5 G
6 H

New file:

1 2
3 4
4 1
5 6

I wanna do the above replacement, how can I do that using awk or some simple command line?

2
  • 2
    Hi! you should try to find a solution first, and then provide an mvce, so we can provide better answers on your issue. Commented Jun 29, 2017 at 20:12
  • Apologies, I did try to look for a solution. I ended up finding one that does replacement in a different way and it didn't have an explanation for the command line. Wanted a better answer than that. Commented Jun 29, 2017 at 20:56

1 Answer 1

1

awk solution:

awk 'NR==FNR{ a[$2]=$1; next }{ $1=a[$1]; $2=a[$2] }1' reffile mainfile

The output:

1 2
3 4
4 1
5 6

  • a[$2]=$1 - capturing numbers from reffile into array indexed by letters (e.g. a["A"]=1)

  • $1=a[$1]; $2=a[$2] - replacing letters in mainfile with respective numbers

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

4 Comments

Thank you! This answers it.
a quick follow up. If the two columns had the same entry, it is only replacing one and removing the other. Is that normal? For example if a row was A A the output comes out to be just 1.
@Blizzard, I've just tested on A A record and it gave me 1 1. Should work
Oh! I had missing values in the ref file. It works splendidly, thank you!

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.