Bash 如何用同一列中上一个单元格的数据填充CSV中的空单元格?

Bash 如何用同一列中上一个单元格的数据填充CSV中的空单元格?,bash,csv,awk,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. bea

我有一个大的标签分开的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

这适用于第1列和第2列:

awk -F '\t' '$1 != ""{p1=$1} NF==3{p2=$2} p1 && $1 == ""{$1=p1} p2 && NF==2{$0=$1 OFS p2 OFS $2} 1' OFS='\t' file
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.

适用于任何缺少的列

awk -F\\t '
{ for (i=1;i<=NF;++i) 
    { if ($i != "") a[i] = $i;
      printf "%s\t", a[i]
    }
  printf RS
}' file
awk-F\\t'

{对于(i=1;i)什么是分隔符?我需要知道的是,例如,您的第5行-我如何判断第一列和第二列都丢失了?为什么第二个示例会导致
awk:fatal:无法打开文件
?@Village:因为我在
-v COL=2
中遗漏了
-v
。抱歉。已修复。
awk -F\\t '
{ for (i=1;i<=NF;++i) 
    { if ($i != "") a[i] = $i;
      printf "%s\t", a[i]
    }
  printf RS
}' file