[英]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: 附加信息:
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. tac
( cat
向后)反向打印文件。 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.