2
votes

here is the problem, there are two files:

aaa.txt:

1       abc
2       def  
3       ghi  
4       jkl  
5       xyz

bbb.txt

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

The question is how to replace first column of file bbb.txt with the corresponding strings from second column of aaa.txt ? Output should look like this:

bbb.txt:

jkl       9  
ghi       2  
ghi       3  
jkl       9  
xyz       8  
def       6  
abc       7

What I come up with already is very slow multiple grep use:

cat bbb.txt | awk '{print $1}' | while read k; 
do res=$(grep $k aaa.txt | awk '{print $2}'); 
echo $res >> out
done

But it does not do the job at all and i have this suspicion that its way easier to do..

Thanks!

4

4 Answers

3
votes

Bash:

dict=()
while read key value; do
  dict[$key]=$value
done < aaa.txt

while read key text; do
  echo "${dict[$key]} $text"
done < bbb.txt
2
votes

quick and dirty:

kent$  awk 'NR==FNR{a[$1]=$2;next;}$1=a[$1]' aaa.txt bbb.txt 
jkl 9
ghi 2
ghi 3
jkl 9
xyz 8
def 6
abc 7
0
votes

This might work for you:(GNU sed?)

sed 's/^\(\S*\)\s*\(\S*\).*/s|^\1\\>|\2|/' aaa.txt | sed -i -f - bbb.txt

In essence, convert the aaa.txt into a sed script which looks like so:

sed 's/^\(\S*\)\s*\(\S*\).*/s|^\1\\>|\2|/' aaa.txt                   
s|^1\>|abc|
s|^2\>|def|
s|^3\>|ghi|
s|^4\>|jkl|
s|^5\>|xyz|

Then pipe this through to a second sed program that runs these instructions against bbb.txt

0
votes

Is order important? If not how about

join -t $'\t' <(sort -n aaa.txt) <(sort -n bbb.txt) | cut -d$'\t' -f2-