sed / awk - 使用模式匹配后插入空格

时间:2018-04-11 13:40:23

标签: regex awk sed

我正在尝试使用sed在csv文件中全局查找和替换,其中每个字段由“并且由...分隔,但字段的某些内容也可以包含”。 我试图找到字段中最后一个字符为“并在此之后插入一个空格的位置,以便字段以空格而不是”结尾。 请注意,一行中可能有多个字段,其中字段的最后一个字符可能是“。

例如,这里有一些文件内容(4行)...

"123","def","","",""
"456","seven eight "nine" ten","","",""
"789"."twenty thirty sixty "seven"","","",""
"303030","one two "three" "four"","five "six"","",""

它应该变成......

"123","def","","",""
"456","seven eight "nine" ten","","",""
"789"."twenty thirty sixty "seven" ","","",""
"303030","one two "three" "four" ","five "six" ","",""

即。插入空间的3个位置:第3行一次,第四行两次。

目前我得到了:

1,$ s/[^,]"",/" ",/g

所以它找到了所有匹配项,但在匹配前没有保留字符,所以我得到了结果......

"123","def","","",""
"456","seven eight "nine" ten","","",""
"789"."twenty thirty sixty "seve" ","","",""
"303030","one two "three" "fou" ","five "si" ","",""

如何使用sed获得所需的输出?或者也许是用awk?

感谢。

1 个答案:

答案 0 :(得分:1)

您需要创建一个捕获组并使用替代参考:

sed -E 's/([^,"])""/\1" "/g' file

"123","def","","",""
"456","seven eight "nine" ten","","",""
"789"."twenty thirty sixty "seven" ","","",""
"303030","one two "three" "four" ","five "six" ","",""

保存更改内联使用:

sed -i.bak -E 's/([^,"])""/\1" "/g' file