New User
New User

Reputation: 10349

How to read 1 line from 2 files sequentially?

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

Answers (4)

nrp
nrp

Reputation: 441

Just in case it might be helpful to somebody. Different ways to achieve this, here are 2 simple examples.

  1. In this example the lines number is read from one of the files, it is assumed that we move counting lines in one of the files. Lines counter can be set manually to some number, or the loop can be "while true" as well. 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
  1. If you just need to monitore 2 (or more) files:

tail -F -n1 file1 file2

Result:

==> file1 <==
1619523081232 -- sent msg # 1

==> file2 <==
1619523085287 -- no msgs received

Upvotes: 0

potong
potong

Reputation: 58371

This might work for you (GNU sed though):

sed 'R file2' file1

Upvotes: 3

k06a
k06a

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

jaypal singh
jaypal singh

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

Pure Bash Solution using file descriptors:

<&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

Paste Utility:

[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

Related Questions