Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single column data to multiple columns

I have data of positive or negative floating point values in a single column which is separated by two empty lines.

1.0
-2.0


3.0
4.0


-5.0
6.0


-7.0
8.0

In bash, what would be the best way to get this data into multiple columns so that the end result looks something like this:

1.0 3.0 -5.0 -7.0
-2.0 4.0 6.0 8.0

In an ideal situation, the solution would work not only for numbers, but also text separated in a similar way.

like image 236
heuristicus Avatar asked Dec 06 '22 08:12

heuristicus


2 Answers

How about:

$ grep -v '^\s*$' file | pr -ts" " --columns 4 
1.0 3.0 -5.0 -7.0
-2.0 4.0 6.0 8.0

grep is used to remove the blank lines and pr to format the output.

like image 193
Chris Seymour Avatar answered Dec 14 '22 20:12

Chris Seymour


This might work for you (GNU sed):

sed -r '/./!d;$!N;2{h;d};G;s/^(.*)\n(.*)\n(.*)\n(.*)$/\3 \1\n\4 \2/;$!{h;d}' file
  • /./!d if the line does not contain a character delete it.
  • $!N if the line is not the last append a newline and the following line to the pattern space (PS).
  • 2{h;d} for the second line, copy the PS to the hold space(HS) and then delete it.
  • G for all other lines append the HS to the PS.
  • s/^(.*)\n(.*)\n(.*)\n(.*)$/\3 \1\n\4 \2/ re-arrange the PS into the order that is required.
  • $!{h;d}for all line except the last copy the PS to the HS and then delete the PS. This means that on encountering the last the line the contents of the PS will be printed out.
like image 21
potong Avatar answered Dec 14 '22 19:12

potong