Home > Blockchain >  assign a value from a list to corresponding string on terminal
assign a value from a list to corresponding string on terminal

Time:02-13

I am trying to do create a list with assigning the corresponding values from another list.

I have a file like this(list.txt);

.
.
ak_1002
ak_1002
ak_1014
ak_1017
ak_1017 
ak_1239
ak_1246
ak_1284
ak_1286
ak_1320
ak_138
ak_139
.
.

And another file with the corresponding values (ref.txt)

.
.
ak_1     39,877
ak_10    75,636
ak_100   32,936
ak_1000  81,609
ak_1002  30,946
ak_1003  40,862
ak_1004  96,566
ak_1005  50,778
ak_1006  62,698
ak_1007  47,8
ak_1008  37,895
ak_1009  126,501
ak_101   45,829
ak_1011  33,925
ak_1012  50,778
ak_1013  43,842
ak_1014  65,676
ak_1015  161,859
ak_1016  70,652
ak_1017  32,933
.
.

I am trying to obtain a result file should be looking like this:

.
.
ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933 
.
.

Actually, I was using this code with other datasets and it was working perfectly, but right now it is returning no result.

awk 'FNR==NR{ arr[NR]=$0 }
    NR!=FNR{ for(i in arr){
      if(arr[i]==$1){ print arr[i],$2 } } }' list.txt ref.txt > result.txt

I could not figure out the reason. If you have any idea thank you in advance.

CodePudding user response:

You can use the join command:

join list.txt ref.txt
ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933

Update: handling CRLF line endings in list.txt:

#!/bin/bash

join <(sed $'s/\r$//' list.txt) ref.txt

CodePudding user response:

Using awk,

awk -v RS='\n|\r\n' 'FNR==NR{ arr[$1]=$2 }
     FNR!=NR{ if ($1 in arr) print $1, arr[$1]; }' ref.txt list.txt
  • Related