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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sed / awk - 使用模式匹配后插入空格相关的知识,希望对你有一定的参考价值。

我正在尝试使用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?

谢谢。

答案

您需要创建一个捕获组并使用反向引用替换:

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

以上是关于sed / awk - 使用模式匹配后插入空格的主要内容,如果未能解决你的问题,请参考以下文章

使用 sed 或 awk 按照匹配模式打印一行

文本三剑客之awk

Sed - 在两个字符串之间的匹配模式后插入带文本的行

使用 sed/awk 仅打印包含匹配模式的单词 - 以 /pattern/ 开头或以 /pattern/ 结尾的单词

awk / sed:如果任何字段与模式匹配,则替换所有字段

sed 或 awk:删除模式后面的 n 行