bash - 如何使用同一列中前一个单元格的数据填充 CSV 中的空单元格?

标签 bash csv awk

我有一个很大的制表符分隔的 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/

相关文章:

bash - awk gensub 函数使用问题

c - 通过标准输入发送 SIGINT

javascript - 将 Html 表格内容导出到具有自定义文件名的 CSV 文件(应该在 IE 中工作)

bash - 将 GLOBIGNORE 传递给 bash 调用

csv - 将唯一的连续行号添加到 pyspark 中的数据框

python - 如何使用行数和列名从 CSV 文件调用组件

vim - 转换文件每行一个字

linux - 通过 Bash 更改 txt 文件

bash - 为什么 Bash 在制表符完成变量名称时不能忽略大小写?

Linux Bash 脚本 - 想要在执行其他任务时在控制台上运行秒表