我有一个很大的制表符分隔的 CSV 文件。但是,它缺少一些数据:
1 cat The cat ate the fish.
dog The dog played in the yard.
fish The fish went to the river.
2 eagle The eagle flew in the sky.
The eagle stopped in the mountains.
bear The bear ate the honey.
我需要用前一行中出现的任何数据填充所有空单元格。输出将如下所示:
1 cat The cat ate the fish.
1 dog The dog played in the yard.
1 fish The fish went to the river.
2 eagle The eagle flew in the sky.
2 eagle The eagle stopped in the mountains.
2 bear The bear ate the honey.
- 最好,该方法一次仅编辑一个指定的列,并且必须针对指定的不同列运行多次,才能完全填充整个 CSV。
有没有办法用具有数据的同一列中的前一个单元格的内容填充 CSV 中的空单元格?
最佳答案
awk 解决整个文件:
awk -F\\t '
{
for (i=1;i<=NF;++i) if ($i != "") a[i] = $i;
if (na < NF) na = NF;
for (i=1;i<na;++i) printf "%s\t", a[i]
printf "%s\n", a[na];
}
' file.tsv
仅执行指定列:
awk -F\\t -v COL=2 '
$COL=="" {$COL = saved}
{saved = $COL; print}
' file.tsv
关于bash - 如何使用同一列中前一个单元格的数据填充 CSV 中的空单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419438/