Reputation: 99
I have 2 file. Let's say file1 and file2. I want to read the file1 together with the file2 so it will give me an output into one single line.
eg. file1 = contents "123.45.67.89" file2 = contents "hostname.cco"
output: 123.45.67.89 hostname.cco
Im runninng nested loop but seems I can not accoumplish what I want to do.
Upvotes: 2
Views: 48
Reputation: 84521
It's actually quite simple, but it does require reading from more than one file descriptor. Essentially, you set up a read loop, as normal, and redirect a file to fd3
and a second file on stdin
, you can then read independent lines from each file on each iteration of the loop. (e.g. read line1 from file1, line1 from file2, and so on). You can use:
#!/bin/bash
while read -r -u 3 linea; do ## reads linea from file1
read -r lineb; ## reads lineb from file2
printf "%s %s\n" "$linea" "$lineb" ## outputs combined lines
done 3<"$1" <"$2" ## notice first file on fd3 and 2nd on stdin
exit 0
Example Use/Output
Then using your file content for file1
and file2
, you would get the following output:
$ bash read2fd.sh file1 file2
123.45.67.89 hostname.cco
If that is not what you intended, please let me know and I'm happy to help further.
Upvotes: 1