在 sed 脚本中将小于 100 的数字替换为字符串的正则表达式

问题描述 投票:0回答:1

我正在 .sed 脚本中测试正则表达式来替换数字 < 100. I have to change numbers lower than 100 only in the fifth field of the CSV.

CSV 以逗号分隔。

CSV 示例:

datetime,car,brand,model,km,new
10/10/1949 20:30,yes,ford,f150,20,yes
10/10/1949 20:30,no,yamaha,r7,1560,yes
10/10/1949 20:30,yes,renault,twingo,37,yes
10/10/1949 20:30,no,honda,cbr600rr,2000,no

我有这个脚本:

# Replace
s/\([^,]*,[^,]*,[^,]*,[^,]*,\)\(0\|[1-9][0-9]\{0,1\}\)\([^,]*\)/\1none\3/

终端中的答案必须是:

datetime,car,brand,model,km,new
10/10/1949 20:30,yes,ford,f150,none,yes
10/10/1949 20:30,no,yamaha,r7,1560,yes
10/10/1949 20:30,yes,renault,twingo,none,yes
10/10/1949 20:30,no,honda,cbr600rr,2000,no

我运行脚本

sed -f script.sed ./sample.csv

答案是

datetime,car,brand,model,km,new
10/10/1949 20:30,yes,ford,f150,none,yes
10/10/1949 20:30,no,yamaha,r7,none60,yes
10/10/1949 20:30,yes,renault,twingo,none,yes
10/10/1949 20:30,no,honda,cbr600rr,none00,no

它总是替换第一个数字,而不仅仅是数字为 0-99 的字段。

编辑:我不能使用 awk 来实现这一点。

你能帮我吗?

非常感谢。

致以诚挚的问候。

regex bash sed
1个回答
0
投票

用户 Barnar 在第一条评论中解决了这个问题。

在最后一组中,我必须将 ([^,]) 更改为 (,[^,])

解决办法是

# Replace
s/\([^,]*,[^,]*,[^,]*,[^,]*,\)\(0\|[1-9][0-9]\{0,1\}\)\([^,]*\)/\1none\3/

谢谢大家。

© www.soinside.com 2019 - 2024. All rights reserved.