简体   繁体   English

重击-在列中用以下值填充空单元格

[英]Bash - fill empty cell with following value in the column

I have a long tab-delimited CSV file and I am trying to paste in a cell a value that comes later on the column. 我有一个由制表符分隔的长CSV文件,我试图将一个值粘贴到单元格中,该值稍后会出现在列中。 For instance, input.txt: 例如,input.txt:

0 
1 
1.345 B
2
2.86 A
3
4

I would like an output such as: 我想要这样的输出:

0 B
1 B
1.345 B
2 A
2.86 A
3 B
4 B

I've been tinkering with code from other threads like this awk solution , but the problem is that the value I want is not before the empty cell, but after, kind of a .FillUp in Excel. 我一直在修改其他线程(如awk解决方案)中的代码,但问题是我想要的值不是在空单元格之前,而是在Excel中的.FillUp之后。

Additional information: 附加信息:

  • input file may have different number of lines 输入文件的行数可能不同
  • "A" and "B" in input file may be at different rows and not evenly separated 输入文件中的“ A”和“ B”可能在不同的行中并且没有均匀地分开
  • second column may have only two values 第二列可能只有两个值
  • last cell in second column may not have value 第二列中的最后一个单元格可能没有值
  • [EDIT] for the last two rows in input.txt, B is known to be in the second column, as all rows after 2.86 are not A. [edit]对于input.txt的最后两行,已知B位于第二列,因为2.86之后的所有行都不是A。

Thanks in advance. 提前致谢。

$ tac input.txt | awk -v V=B '{if ($2) V=$2; else $2=V; print}' | tac
0 B
1 B
1.345 B
2 A
2.86 A
3 B
4 B

tac ( cat backwards) prints a file in reverse. taccat向后)反向打印文件。 Reverse the file, fill in the missing values, and then reverse it again. 反转文件,填写缺少的值,然后再次反转。

This allows you to process the file in a single pass as long as you know the first value to fill. 只要您知道要填充的第一个值,就可以单次处理文件。 It should be quite a bit faster than reversing the file twice. 它应该比两次反转文件要快得多。

awk 'BEGIN {fillvalue="B"} $2 {fillvalue=$2=="A"?"B":"A"} !$2 {$2=fillvalue} 1' input.txt

Note that this assumes knowledge about the nature of that second column being only 'A' or 'B' or blank. 请注意,这是假设有关第二列的性质的知识仅为“ A”或“ B”或空白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM