首页 > 解决方案 > looping over different list files, retrieving always the sam Eline

问题描述

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

标签: listloopsunixecho

解决方案


快速尝试,如果这是您需要的:

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

...输出是:

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

文件也应该关闭:

exec 4<&-
exec 5<&-

重点是做一个循环,一次从 3 个不同的文件中读取一行。为输入而打开的文件 (exec ...< ...) 至少应包含与控制循环的主文件相同的行数。

可以在这里找到一些参考:文件描述符如何工作?

或对 bash 文件描述符进行一些研究。希望能帮助到你。


推荐阅读