如何用sed替换空双引号""但保留|""格式?
问题描述
需要用sed工具把文件里的空双引号""替换成~,但得保留|""这种格式。现有文件片段如下:
"740b3d39-7676-485a-b3d6-041f6af273e5"|"8917963"|"BDSA-2021-3803"|"CVE-2021-4102"|"BDSA"|"NEW"|""|""|""|"Chromium is vulnerable to a use-after-free (UAF) issue in the `V8` functionality.A remote attacker could trick a victim user into viewing a crafted HTML page in order to trigger the UAF flaw and cause memory corruption.**Note**: Google has reported that they are ""aware of reports that an exploit for CVE-2021-4102 exists in the wild."" This vulnerability is listed as exploitable by the Cybersecurity & Infrastructure Security Agency in their Known Exploited Vulnerabilities Catalog."|"MEDIUM"|"6.8"|"8.6"|"6.4"|""|"HIGH"|"8.8"|"2.8"|"5.9"|"8.2"|"NETWORK"|"True"|"False"|"2021-12-17 12:59:04.779000+00:00"|"2022-12-13 14:15:49.529000+00:00"|""|""
试了这个命令:
sed "/\|\"\"/ s/\"\"/~/g" <file_name>
结果它把所有""都替换了,不符合要求,求正确的sed命令。
解决方案
方法1:反向否定预查(GNU sed适用)
这个方法最直观,直接排除|后面的"":
sed -E 's/(?<!\|)""/~/g' <file_name>
-E:开启扩展正则语法,简化表达式写法(?<!\|):反向否定预查,确保""的前面不是|,精准避开|""的场景/~/g:全局替换所有符合条件的""为~
方法2:兼容全版本sed
如果你的sed不支持反向预查(比如BSD sed),可以用分组匹配实现同样效果:
sed 's/\(^\|[^|]\)""/\1~/g' <file_name>
这个命令会匹配两种场景的"":
- 行开头的
"" - 前面不是
|字符的""
然后保留前面的字符,只替换后续的""为~,同样不会修改|""格式。
内容的提问来源于stack exchange,提问作者Stas Becker
相关产品推荐
相关产品推荐

