Single column data to multiple columns Single column data to multiple columns shell shell

Single column data to multiple columns


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.


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.


This is a longer but more readable solution:

a=() b=() i=0while read line ; do    case $i in        0) a+=($line) ;;        1) b+=($line) ;;    esac    ((i++))    if ((i == 4)); then i=0; fidone < data.txtecho ${a[*]}echo ${b[*]}