删除虚假逗号

2023-12-26

一位白痴客户正在生成 csv 文件,但其中一个字段(描述字段)有时有多余的逗号。

是否有一个整洁的正则表达式来查找这些不良记录并用其他内容替换多余的逗号。 SED 命令行就可以了。

Example:

A,B,C,This is a description,D,E
F,G,H,This is a description with a comma (,) in it,D,E

我需要一个 SED 来判断该行中有太多逗号,并从字段 4 中删除多余的逗号。

我们没有能力告诉愚蠢的客户更改他们的代码。

Added

我不会反对仅删除的解决方案one我必须运行多次的虚假逗号。


方案一:单行,删除,

下面是 SED 的一句台词:

sed -r 's/([^,],[^,],[^,],)(.*)(,.+,.+)/\1'"$(sed -r 's/([^,],[^,],[^,],)(.*)(,.+,.+)/\2/' <<< $myInput | sed 's/,//g')"'\3/' <<< $myInput

你必须更换<<< $myInput无论您的实际输入是什么。
当您使用 CSV 时,您可能需要调整(两次出现)正则表达式以匹配 CSV 工作表的每一行。
如果您的前三个和最后两个字段大于一个字符,请替换[^,] with [^,]*.

解释:
我们使用这个正则表达式

/([^,],[^,],[^,],)(.*)(,.+,.+)/

它捕获第一个(F,G,H,), 第二 (.*)和最后一部分(,D,E)为我们提供了字符串。
第一和第三捕获组将保持不变,而第二捕获组将被替换。
对于我们所说的替换sed第二次(实际上是第三次)。首先我们只捕获第二组,其次我们替换每一个,什么都没有(仅在捕获组中!)。

Proof: enter image description here

Of course, if there is no unwanted comma, nothing gets replaced: enter image description here


## Solution 2: whole file, line-by-line, delete `,` ## If you want to specify only **a file** and the replacement should happen for each line of the file you can use
while read line; do sed -r 's/([^,],[^,],[^,],)(.*)(,.+,.+)/\1'"$(sed -r 's/([^,],[^,],[^,],)(.*)(,.+,.+)/\2/' <<< $line | sed 's/,//g')"'\3/' <<< $line; done < input.txt

where input.txt最后显然是你的文件。
我只是在a中使用上面的SED命令while-loop 读取文本的每一行。这是必要的,因为您必须在调用时跟踪正在读取的行sed在同一输入上两次。


## Solution 3: whole file, enclose field in `"` ## As [@Łukasz L.][4] pointed out in the comments to the OP, according to the [RFC1480][5], which describes the format for CSV-files it would be better to enclose fields which contain a comma in `"`. This is more simple than the other solutions:
sed -r 's/([^,],[^,],[^,],)(.*)(,.*,.*)/\1"\2"\3/' input.txt

我们再次拥有三个捕获组。这使我们可以简单地将第二组包装在"!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

删除虚假逗号 的相关文章

随机推荐