awk using 2 input files instead of while loops

Hi Friends,

I have two files as input with data that looks like this:
file1.txt

1
2
3
4

file2.txt

a,aa
b,bb
c,cc
d,dd
e,ee
f,ff

instead of me doing 2 while loops to get the combinations

   while read line_file1
   do
         while read line_file2
         do
                1stpos="$(echo $line_file2 | cut -d "," -f1)"
                2ndpos="$(echo $line_file2 | cut -d "," -f2)"            
            
                printf "%-20s%-20s%-20s" ${1stpos} ${2ndpos} $(line_file1) >> output.txt
         done < file2.txt
   done < file1.txt

The output should look like this:

a           aa          1   
b           bb          1
c           cc          1
d          dd          1
e          ee           1
f           ff            1
a          aa           2
b          bb          2
c          cc           2
d          dd          2
...

<-- assuming that the output file is in a fixed length format since columns are not aligned :slight_smile:

can this be done using awk? or sed? to speed up the process of looping; because in reality, data is could be very enormous and could lead to performance issues. please help.... thanks!

PS.

Is there also a way to improve this?

while read line_file2
do
  1stpos="$(echo $line_file2 | cut -d "," -f1)"
  2ndpos="$(echo $line_file2 | cut -d "," -f2)"            
  printf "%-20s%-20s%-20s" ${1stpos} ${2ndpos} $(line_file1) >> output.txt  done < file2.txt

can we turn the red lines into an awk to get rid of the slow echo?
Thanks!

Can you post desired output for those two input files?

I hope this will anwer your query

 awk  'NR==FNR{a[$1]=$1;next} {for(v in a){ print v","$0 | "sort -n -k1"   }}' file1 file2
1 Like