VIM 填充适当数量的“,0”以获得CSV文件

VIM padding with appropriate number of ",0" to get CSV file

我有一个包含数字的文件,例如

 1, 2, 3
 4, 5
 6, 7, 8, 9,10,11
12,13,14,15,16
...

我想通过填充每一行来创建一个 CSV 文件,这样就有 6 个值用 5 个逗号分隔,所以我需要在每一行中添加适当数量的“,0”。它应该看起来像

 1, 2, 3, 0, 0, 0
 4, 5, 0, 0, 0, 0
 6, 7, 8, 9,10,11
12,13,14,15,16, 0
...

如何使用 VIM 执行此操作?

我可以使用正则表达式计算一行中“,”的数量,并使用替换 s 命令在每一行中添加正确数量的“,0”吗?

您可以先在所有行中添加六个零,无论它们有多少个数字,然后您可以删除每行中从第六个逗号到末尾的所有内容。

要插入它们,

        :1,$ normal! i,0,0,0,0,0,0

删除从第六个逗号到结尾,

        :1,$normal! ^6f,D

      ^ moves to first character in line(which is obviously a number here)

       6f,  finds comma six times

        D delete from cursor to end of line 

示例:

原创

             1,2,
             3,6,7,0,0,0
             4,5,6
            11,12,13

加上六个零后,

             1,2,0,0,0,0,0,0
             3,6,7,0,0,0,0,0,0,0,0,0
             4,5,6,0,0,0,0,0,0
            11,12,13,0,0,0,0,0,0

从六个逗号删除到行尾后

             1,2,0,0,0,0,0
             3,6,7,0,0,0,0
             4,5,6,0,0,0,0
            11,12,13,0,0,0

您可以通过输入以下命令来实现:

:g/^/ s/^.*$/&,0,0,0,0,0,0/ | normal! 6f,D

perl:

perl -lpe '$_ .= ",0" x (5 - tr/,//)' file.txt

awk:

awk -v FS=, -v OFS=, '{ for(i = NF+1; i <= 6; i++) $i = 0 } 1' file.txt

sed:

sed ':b /^\([^,]*,\)\{5\}/ b; { s/$/,0/; b b }' file.txt

至于如何从内部 Vim 执行此操作 ,您还可以通过外部程序传输文本,它将用输出替换输入。这是利用排序、重复数据删除、基于 grep 的过滤等或 Sato 的一些建议的简单方法。因此,如果您有一个名为 standardize_commas.py 的脚本,请尝试使用视线模式 select 编辑您的块(shift+v 然后 select),然后输入类似 :! python /tmp/standardize_commas.py 的内容。它应该在该字符串前加一点,表示该命令将 运行 在当前 selected 行上。

仅供参考,这是我的 /tmp/standardize_commas.py 脚本:

import sys

max_width = 0
rows = []
for line in sys.stdin:
    line = line.strip()
    existing_vals = line.split(",")
    rows.append(existing_vals)
    max_width = max(max_width, len(existing_vals))

for row in rows:
    zeros_needed = max_width - len(row)
    full_values = row + ["0"] * zeros_needed
    print ",".join(full_values)