Wednesday, October 14, 2009

Insert lines from files using Linux paste command


I have already put a post on some good uses of Linux/UNIX 'paste' command; lets check another practical one using paste command.

Input files:

$ cat contestant.txt
Christopher
Williams
Darwin
Ajay
Brain
Amay
Jiten
Lila

$ cat leader.txt
Mr B
Mrs C
Mrs A

Output required:

For every single line of 'leader.txt'; insert 3 lines from file 'contestant.txt'; so that the output looks like this:

Mr B
Christopher
Williams
Darwin
Mrs C
Ajay
Brain
Amay
Mrs A
Jiten
Lila


The step by step solution using Linux/UNIX paste command

$ cat contestant.txt | paste - - -
Output:
Christopher Williams Darwin
Ajay Brain Amay
Jiten Lila

$ cat contestant.txt | paste - - - | paste leader.txt -
Output:
Mr B Christopher Williams Darwin
Mrs C Ajay Brain Amay
Mrs A Jiten Lila

$ cat contestant.txt | paste - - - |paste leader.txt - |tr "\t" "\n"
Output:
Mr B
Christopher
Williams
Darwin
Mrs C
Ajay
Brain
Amay
Mrs A
Jiten
Lila

Another similar one liner for the same:

$ < contestant.txt paste - - - | paste leader.txt - | tr "\t" "\n"

No comments:

© Jadu Saikia www.UNIXCL.com