Reputation: 10349
How do I read from 2 files 1 line at a time? Say if I have file1 and file2 with following content:
file1:
line1.a
line2.a
line3.a
file2:
line1.b
line2.b
line3.b
How do I get output like this -
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
...
...
Upvotes: 12
Views: 15681
Reputation: 441
Just in case it might be helpful to somebody. Different ways to achieve this, here are 2 simple examples.
Head -n<N> | tail -n1
can be used instead of sed
if needed.
Sleep
is put for more convenient reading.i=0; k="$(wc -l file1 | awk '{print $1}')"; while [ $i -lt $k ]; do ((i++)); sed -n "$i"p file1; sed -n "$i"p file2; echo "---------------"; sleep 1; done
Result:
1619523081232 -- sent msg # 1
1619523085287 -- no msgs received
---------------
1619523082233 -- sent msg # 2
1619523085296 -- 1 msgs received
tail -F -n1 file1 file2
Result:
==> file1 <==
1619523081232 -- sent msg # 1
==> file2 <==
1619523085287 -- no msgs received
Upvotes: 0
Reputation: 18745
C#:
string[] lines1 = File.ReadAllLines("file1.txt");
string[] lines2 = File.ReadAllLines("file2.txt");
int i1 = 0;
int i2 = 0;
bool flag = true;
while (i1+i2 < lines1.Length + lines2.Length)
{
string line = null;
if (flag && i1 < lines1.Length)
line = lines1[i1++];
else if (i2 < lines2.Length)
line = lines2[i2++];
else
line = lines1[i1++];
flag = !flag;
Console.WriteLine(line);
}
Upvotes: 0
Reputation: 77085
You can do it either via a pure bash
way or by using a tool called paste
:
Your files:
[jaypal:~/Temp] cat file1
line1.a
line2.a
line3.a
line4.a
[jaypal:~/Temp] cat file2
line1.b
line2.b
line3.b
line4.b
<&3 tells bash to read a file at descriptor 3. You would be aware that 0, 1 and 2 descriptors are used by Stdin, Stdout and Stderr. So we should avoid using those. Also, descriptors after 9 are used by bash internally so you can use any one from 3 to 9.
[jaypal:~/Temp] while read -r a && read -r b <&3; do
> echo -e "$a\n$b";
> done < file1 3<file2
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
line4.a
line4.b
[jaypal:~/Temp] paste -d"\n" file1 file2
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
line4.a
line4.b
Upvotes: 32