Sequential Reading from two file in a loop

Hello All,

I have two files with me file1.txt and file2.txt

file1.txt has:

333
222
111

file2.txt has

ccc
bbb
aaa

ccc is related to 333 only, bbb is related to 222 only and aaa is related to 111 only.

I have to get the values from each of the file and pass them in the URL like:

https://red.com/$(first value from file1.txt)/${first value from file2.txt}
https://red.com/$(second value from file1.txt)/${second value from file2.txt}

I wrote a nested for reading each of them line by line but obviously, the inner loop for file2 runs 3 times for processing first record of the first loop.

Any help please?

Please become accustomed to provide decent context info of your problem.
It is always helpful to support a request with system info like OS and shell, related environment (variables, options), preferred tools, adequate (representative) sample input and desired output data and the logics connecting the two, and, if existent, system (error) messages verbatim, to avoid ambiguities and keep people from guessing.

Should your desire be to solve above in shell, and yours is bourne compatible, there are many threads dealing with and presenting solutions to your problem. A very simplified approach would be to use redirection from extra file descriptors:

exec 3<file1 4<file2
while read X <&3 && read Y <&4; do echo $Y $X; done
ccc 333
bbb 222
aaa 111
exec 3<&- 4<&-
1 Like

Have you tried the paste command?

paste file1.txt file2.txt

The output will be from the same line number from each file separated with a tab unless you choose some other character. The output can be piped or redirected like other unix commands.

ccc\t333
bbb\t222
aaa\t111
1 Like

The shell has builtin output formatting.
With redirection of the while block there is no need to cancel the redirection afterwards

while read val1 <&3 && read val2 <&4
do
  echo "https://red.com/$val1/$val2"
done 3<file1.txt 4<file2.txt
1 Like