How to merge lines with fixed interval in a file

text processing

I have a file and its content looks like this:

a1
b1
c1
aa
bb
cc
aaa
bbb
ccc
d1
e1
f1
dd
ee
ff
ddd
eee
fff
g1
h1
i1
gg
hh
ii
ggg
hhh
iii

What's the best way to merge the rows with fixed interval (3 in this case) and get something like:

a1 aa aaa
b1 bb bbb
c1 cc ccc
d1 dd ddd
e1 ee eee
f1 ff fff
g1 gg ggg
h1 hh hhh
i1 ii iii

The algorithm to get the out put from the input is:

  • First we get row 1 which is a1.
  • We know the interval is 3
  • So row 1, row (1+3), row (1+3+3) should be on the same row
  • Similarly, row 2, 5, 8 should be on the same row etc.

Those a1, aa and aaa etc. are just random dummy text and they could be any random string. The point is that there is a fixed interval between a1, aa and aaa.

Currently I use emacs keyboard macro to do this task. However I want to know if there are any better ways to solve this problem. Thanks in advance.

Best Answer

If you're on gnu/anything and the number of lines is multiple of 9, you could run

split -l9 --filter='pr -3 -s" " -t' infile

This splits the input into pieces of nine lines and each piece is piped to pr -3 -s" " -t' which columnates it... Depending on the no. of lines and their length you may need to play with pr options -w and -l. See the man page for more details.

Related Question