问题描述
我有一个CSV文件,其中某些列为空,例如
I have a CSV file where some columns are empty such as
oski14,safe,0,13,53,4
oski15,Unknow,,,,0
oski16,Unknow,,,,0
oski17,Unknow,,,,0
oski18,unsafe,0.55,,1,2
oski19,unsafe,0.12,4,,56
如何将所有空列替换为空"一词.我尝试使用awk(这是我正在学习使用的命令).
How do I replace all the empty columns with the word "empty".I have tried using awk(which is a command I am learning to use).
我想要
oski14,safe,0,13,53,4
oski15,Unknow,empty,empty,empty,0
oski16,Unknow,empty,empty,empty,0
oski17,Unknow,empty,empty,empty,0
oski18,unsafe,0.55,empty,1,2
oski19,unsafe,0.12,4,empty,56
我试图只替换第3列,以查看我是否在正确的轨道上
I tried to replace just the 3rd column to see if I was on the right track
awk -F '[[:space:]]' '$2 && !$3{$3="empty"}1' file
这给我留下了
oski14,safe,0,13,53,4
oski15,Unknow,,,,0
oski16,Unknow,,,,0
oski17,Unknow,,,,0
oski18,unsafe,0.55,,1,2
oski19,unsafe,0.12,4,,56
我也尝试过
nawk -F, '{$3="\ "?"empty":$3;print}' OFS="," file
这导致了
oski14,safe,empty,13,53,4
oski15,Unknow,empty,,,0
oski16,Unknow,empty,,,0
oski17,Unknow,empty,,,0
oski18,unsafe,empty,,1,2
oski19,unsafe,empty,4,,56
最后我尝试了
awk '{if (!$3) {print $1,$2,"empty"} else {print $1,$2,$3}}' file
这给我留下了
oski14,safe,empty,13,53,4 empty
oski15,Unknow,empty,,,0 empty
oski16,Unknow,empty,,,0 empty
oski17,Unknow,empty,,,0 empty
oski18,unsafe,empty,,1,2 empty
oski19,unsafe,empty,4,,56 empty
推荐答案
具有支持带有-E
参数的ERE的sed(例如GNU sed或OSX/BSD sed):
With a sed that supports EREs with a -E
argument (e.g. GNU sed or OSX/BSD sed):
$ sed -E 's/(^|,)(,|$)/\1empty\2/g; s/(^|,)(,|$)/\1empty\2/g' file
oski14,safe,0,13,53,4
oski15,Unknow,empty,empty,empty,0
oski16,Unknow,empty,empty,empty,0
oski17,Unknow,empty,empty,empty,0
oski18,unsafe,0.55,empty,1,2
oski19,unsafe,0.12,4,empty,56
您需要进行两次替换,因为给定连续逗号(例如,,,
),一个正则表达式匹配将用完前2个,
,因此您将剩下,empty,,
.
You need to do the substitution twice because given contiguous commas like ,,,
one regexp match would use up the first 2 ,
s and so you'd be left with ,empty,,
.
上面的代码会将一个完全空的行更改为empty
,请让我们知道这是否是一个问题.
The above would change a completely empty line into empty
, let us know if that's an issue.
这篇关于填充CSV文件中的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!