将单列转换为多列,确保最后一行的列数

MyI*_*ICQ 4 csv awk

我想使用 AWK (Windows) 将单列文本文件转换为多列 - 脚本或命令行中指定的计数。

这个问题之前已经被问过,但我的最终数据文件需要始终具有相同的列数。

输入示例:

L1
L2
L3
L4
L5
L6
L7
Run Code Online (Sandbox Code Playgroud)

分为 3 列和“;” 作为分隔符

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.
Run Code Online (Sandbox Code Playgroud)

我尝试修改给定的典型解决方案的变体:NR%4 {printf $0",";next} 1; 和计数器,但无法完全正确。

我不想之前计算行数,从而多次运行该文件。

anu*_*ava 5

您可以使用这个awk解决方案:

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;;
Run Code Online (Sandbox Code Playgroud)