假设 CSV 中有一行如下所示:
|Foo|,,,,,,,,|Bar|,,,,,
其中 |
是外部封装器,,
是外部分隔符(如您所料)。
但是假设您有一些代码需要填充这些空字段,并且您希望将此行转换为如下所示:
|Foo|,||,||,||,||,||,||,||,|Bar|,||,||,||,||,
(我们可以稍后处理尾随的逗号) 我尝试在此 CSV 上使用此 sed 命令来获得所需的结果:
sed 's/,,/,||,/g'
但是,正则表达式模式 ,,
的宽度不为零,因此当它扫描该行时,它会向前移动两个字段,即使我们只处理了一个字段。结果是这样的:
|Foo|,||,,||,,||,,||,|Bar|,||,,||,,
问题是,当我们进行替换时:
|Foo|,||,,,,,,,|Bar|,,,,,
我们已经“处理”了 ||
周围的逗号,我们正则表达式的最后一个逗号之后移至下一对,这并不涉及、||、
的最后一个。
如何使用 sed 进行此替换?
最佳答案
更优雅的方法是使用条件分支:
$ sed ':a;s/,,/,||,/;ta' <<< '|Foo|,,,,,,,,|Bar|,,,,,'
|Foo|,||,||,||,||,||,||,||,|Bar|,||,||,||,||,
来自man sed
:
t label
If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script.
关于csv - 使用 sed 填充 CSV 中的空白字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14777643/