shell

Interlacing file lines

Recently I needed to mix several files into one single file. The point was that I needed to interlace the files so I had all the first lines of every file followed by all the second lines and so on. Put it simply, this is what I had:

fapesteguia@fapesteguia:~/test$ cat file1
file 1 row 1
file 1 row 2
file 1 row 3
file 1 row 4
file 1 row 5
file 1 row 6
file 1 row 7
file 1 row 8
file 1 row 9
file 1 row 10
fapesteguia@fapesteguia:~/test$ cat file2
file 2 row 1
file 2 row 2
file 2 row 3
file 2 row 4
file 2 row 5
file 2 row 6
file 2 row 7
file 2 row 8
file 2 row 9
file 2 row 10
fapesteguia@fapesteguia:~/test$ cat file3
file 3 row 1
file 3 row 2
file 3 row 3
file 3 row 4
file 3 row 5
file 3 row 6
file 3 row 7
file 3 row 8
file 3 row 9
file 3 row 10
fapesteguia@fapesteguia:~/test$

And the expected result was something like this:

file 1 row 1
file 2 row 1
file 3 row 1
file 1 row 2
file 2 row 2
file 3 row 2
...
...

And obviously, the command line came to the rescue. What I did was to use the paste command. paste merges lines from different files. It is almost what I wanted. But paste concatenates (merges) all the first lines into a new first line, all the second lines in a new second line and so on. So for example, if we do:

paste file1 file2

this is what we get:

paste file1 file2
file 1 row 1	file 2 row 1
file 1 row 2	file 2 row 2
...
...

So now the only thing we have to do is to split those lines again by replacing tabs with newlines:

$ paste file1 file2 file3 | sed -e 's/\t/\n/g'
file 1 row 1
file 2 row 1
file 3 row 1
file 1 row 2
file 2 row 2
file 3 row 2
file 1 row 3
file 2 row 3
file 3 row 3
file 1 row 4
file 2 row 4
file 3 row 4
file 1 row 5
file 2 row 5
file 3 row 5
file 1 row 6
file 2 row 6
file 3 row 6
file 1 row 7
file 2 row 7
file 3 row 7
file 1 row 8
file 2 row 8
file 3 row 8
file 1 row 9
file 2 row 9
file 3 row 9
file 1 row 10
file 2 row 10
file 3 row 10

This way we have successfully mixed all the files in a per line basis. It is just incredible how many different problems you can easily solve with a few standard UNIX commands!

Enjoy!

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields