How to concatenate two (file) streams

How to create a stream which sequentially reads from multiple other streams? This is analogous to cat in unix, but for arbitrary streams. In python, something like this might be implemented as:

def cat_streams(s1, s2):
    for line in s1:
        yield line
    for line in s2:
        yield  line

(or some improved version thereof)

But I’m not sure what it would look like in Julia. I know there are task channels which yield, but this is more of a file imitation thing rather than an async thing.

With file1 and file2 set up as

$ echo "line1 in file1\nline2 in file1\nline3 in file1" > file1
$ echo "line1 in file2\nline2 in file2\nline3 in file2" > file2
$ cat file1 file2
line1 in file1
line2 in file1
line3 in file1
line1 in file2
line2 in file2
line3 in file2

you can use Iterators.flatten to concatenate two iterators given by eachline.

julia> for line in Iterators.flatten([eachline("file1"), eachline("file2")])
           println(line)
       end
line1 in file1
line2 in file1
line3 in file1
line1 in file2
line2 in file2
line3 in file2
3 Likes