Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert single column to multiple, ensuring column count on last line

Tags:

csv

awk

I would like to use AWK (Windows) to convert a text file with a single column to multiple columns - the count specified in the script or on the command line.

This question has been asked before but my final data file needs to have the same column count all the way.

Example of input:

L1
L2
L3
L4
L5
L6
L7

split into 3 columns and ";" as a separator

L1;L2;L3
L4;L5;L6
L7;;        <<< here two empty fields are created after end of file, since I used just one on this line.

I tried to modify variants of the typical solution given: NR%4 {printf $0",";next} 1; and a counter, but could not quite get it right.

I would prefer not to count lines before, thereby running over the file multiple times.

like image 338
MyICQ Avatar asked Sep 11 '25 17:09

MyICQ


1 Answers

You may use this awk solution:

awk -v n=3 '{
   sub(/\r$/, "")   # removes DOS line break, if present
   printf "%s", $0(NR%n ? ";" : ORS)
}
END {
   # now we need to add empty columns in last record
   if (NR % n) {
      for (i=1; i < (n - (NR % n)); ++i)
         printf ";"
      print ""
   }
}' file

L1;L2;L3
L4;L5;L6
L7;;
like image 90
anubhava Avatar answered Sep 13 '25 19:09

anubhava