1

I don't know what command should I use in unix.

Let say I have a file like this:

A  23
B  52
C  36
F  25

and second file with 3 columns:

A  aligator  2
B  panda  3
C  bear  4
D  pig  1
E  yeti  0
F  shark  9
G  dog  10
H  cat  1

Now I would like to replace first column values (in 1 file) using the second column values (2 file) if the values from the first columns match between files

example of output:

aligator  23
panda  52
bear  36
shark  25

Can anyone help me?

best.

2 Answers 2

3

If the files are sorted, you can use join from coreutils:

join -o '2.2 1.2' file1 file2

Output:

aligator 23
panda 52
bear 36
shark 25
1

The awk is a good tool for this job:

awk 'NR==FNR{a[$1]=$2;next}a[$1]{print $2,a[$1]}' file1 file2

When first file is being read (FN==FNR) fill array a with values from second column and indexed from first column. Then, when second file is processed print its second column and second column from file1.

Output:

aligator 23
panda 52
bear 36
shark 25
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .