0

I have three files with a list of files I need to use later to apply a function. I have managed to create a loop going through the 3 different files, but no exactly the output I need. My input: rw_sorted_test.txt

1
2
3

fwd_sorted_test.txt

A
B
C

run_list.txt

1st
2nd
3rd

I am running it like this:

    for f in `cat rw_sorted_test.txt`; do for l in `cat fwd_sorted_test.txt`; do for r in `cat run_list.txt` do echo ${f} ${l} ${r}; done; done; done;

What I am obtain now is something like:

1 A 1st
1 A 2nd
1 A 3rd
2 A 1st
2 A 2nd
2 A 3rd
3 A 1st

(...)

What I am looking for is something like:

1 A 1st
2 B 2nd
3 C 3rd

I am sure that it will be something simple, but I am really beginner and all the workarounds have not been working. Also, how can I then make it run after echo my desired output? Thank you

José Dias
  • 57
  • 6
  • If you nest 3 cycles, each made of 3 items, of course you obtain 3**3 = 27 items. If you want only 3 items, you have to use only one cycle (loop). – linuxfan says Reinstate Monica Dec 03 '18 at 14:07
  • how can I transform into one loop and still get the results from each file? I have tried for f in `cat rw_sorted_test.txt` for l in `cat fwd_sorted_test.txt` for r in `cat runlist_test.txt`; do echo${f} ${l} ${r}; done; done; done; but this will lead to the same thing in a different order. I can make it run only 3 times if I put only the first _for_, but then I need to retrieve the lines on the other files. – José Dias Dec 03 '18 at 14:56

2 Answers2

1

Quick try, if it is this that you need:

exec 4< run_list.txt
exec 5< rw_sorted_test.txt
for a in $(cat fwd_sorted_test.txt); do
  read run <&4 
  read sort <&5
  echo "$sort $a $run"
done

...output is:

1 1st A
2 2nd B
3 3rd C

Files should also be closed:

exec 4<&-
exec 5<&-

The whole point is to do a single cycle, and read a line at a time from 3 different files. The files which are opened for input (exec ...< ...) should contain at least the same number of lines as the main file, which is controlling the loop.

Some reference could be find here: How do file descriptors work?

or doing some study on bash file descriptors. Hope it helps.

1

You can use this as a testcase for writing a program in awk:
3 inputfiles, store lines in an array and print everything in an END-block.

In this case you can use another program that works even easier:

paste -d" " rw_sorted_test.txt fwd_sorted_test.txt run_list.txt
Walter A
  • 19,067
  • 2
  • 23
  • 43
  • Such a clever approach. So easy! But yes, I will be using this little things as practicing tools for I can learn. Thank you! – José Dias Dec 04 '18 at 13:17