找到两个字符模式,只替换一个字符

Find two character pattern, replace only one character

在下面的数据中,我想用 ~ 替换所有没有紧跟空格的逗号。因此 "American President, The (1995)" 中的逗号将保留,因为紧接着有空格。

10,GoldenEye (1995),Action|Adventure|Thriller  
11,"American President, The (1995)",Comedy|Drama|Romance

这是我想要的输出:

10~GoldenEye (1995)~Action|Adventure|Thriller  
11~"American President, The (1995)"~Comedy|Drama|Romance

我试过下面的代码,但它替换了两个字符,而不仅仅是第一个字符。

sed 's/,[^ ]/~/g' file.csv 

我得到的输出如下:

10~oldenEye (1995)~ction|Adventure|Thriller  
11~American President, The (1995)"~omedy|Drama|Romance

尝试sed 's/,\([^ \t]\)/~/g' file.csv
这为您提供了请求的输出。
请注意,这不会替换尾随逗号,因此从技术上讲,这只是部分解决方案。
我知道 sed 可以完全按照你的要求做,但我不知道怎么做。
如果您无论如何都不需要转换尾随逗号,那也没关系。

它的作用是找到 ,[^ \t],它是一个逗号后跟一个不是 space 或制表符的字符。 '\(\)可以用来"remember"匹配到什么,然后第一组'\(...\)匹配的值可以引用为。第二组可以引用为\2等

这可能适合您 (GNU sed):

sed -r ':a;s/,(\S|$)/~/g;ta' file

这将替换所有 , 后跟非 space 字符或文件结尾。

N.B。替换是在两个可能的过程中包括相邻的 ,'s

如果您从来没有连续使用 2 个逗号,这将有效:

$ sed -r 's/,([^[:blank:]]|$)/~/g' file
10~GoldenEye (1995)~Action|Adventure|Thriller
11~"American President, The (1995)"~Comedy|Drama|Romance

或:

$ awk '{[=11=]=gensub(/,(\S|$)/,"~\1","g")}1' file
10~GoldenEye (1995)~Action|Adventure|Thriller
11~"American President, The (1995)"~Comedy|Drama|Romance

如果你可以有多个连续的逗号,那么我会坚持使用 awk:

$ awk '{ while( [=12=]!=([=12=]=gensub(/,(\S|$)/,"~\1","g")) ); }1' file
10~GoldenEye (1995)~Action|Adventure|Thriller
11~"American President, The (1995)"~Comedy|Drama|Romance

以下是两种方法的结果if/when 你有连续的逗号:

$ echo 'a,,b' | sed -r 's/,([^[:blank:]]|$)/~/g'
a~,b

$ echo 'a,,b' | awk '{[=13=]=gensub(/,(\S|$)/,"~\1","g")}1'
a~,b

$ echo 'a,,b' | awk '{ while( [=13=]!=([=13=]=gensub(/,(\S|$)/,"~\1","g")) ); }1'
a~~b

以上使用 GNU awk 作为 gensub() 所以我也使用 \S 而不是 [^[:blank]] 因为解决方案需要 GNU awk 所以使用 \S 本身不会牺牲可移植性。如果您使用 GNU sed,它也将支持 \S 而不是 [^[:blank:]],关于其他 seds 的知识。对于其他 awks,它是:

awk '{ while( i=match([=14=],/,([^[:blank:]]|$)/) ) [=14=]=substr([=14=],1,i-1)"~"substr([=14=],i+1) } 1'

第一个 gsub 替换第一行的逗号,接下来的两个 sub 更改第二行的第一个和最后一个逗号。

awk 'NR<2{gsub(/,/,"~")}{sub(/1,/,"1~")}{sub(/,C/,"~C")}1' file
10~GoldenEye (1995)~Action|Adventure|Thriller 
11~"American President, The (1995)"~Comedy|Drama|Romance