方案一:单行,删除,
下面是 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:
Of course, if there is no unwanted comma, nothing gets replaced:
## 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
我们再次拥有三个捕获组。这使我们可以简单地将第二组包装在"
!