Replacing consecutively empty values in a CSV file

2020-07-18 02:46发布

I have a line of text like:

value,value,,,value,value

I want the two empty values to be replaced with a different value. Something like:

value,value,hello,hello,value,value

I'm currently trying something like:

sed -e 's/^,/hello,/' -e 's/,$/,hello/' -e 's/,,/,hello,/g'

That catches blank values at the beginning, end and the middle. BUT, it doesn't catch two consecutive blank values in a row. How can I update the regular expression patterns so that an indefinite number of consecutive blank values can appear in the middle?

标签: regex perl sed
3条回答
【Aperson】
2楼-- · 2020-07-18 02:55

Other perl one-liners:

perl -we '$_=<>; while(s/,,/,hello,/) {}; print;'  value.txt

perl -we 'print join ",", map { $_ || 'hello' } split /,/, <>;' value.txt
查看更多
狗以群分
3楼-- · 2020-07-18 03:00

I don't think you can do it with a single substitute command, since Sed only replaces non-overlapped occurrences of your pattern. This ugly hack could work, but requires you to prevent one more character (I choosed ';') in your values :

$ echo 'value,value,,,value,value' | sed -r 's/,/,;/g;s/(^|;)(,|$)/\1hello\2/g;s/,;/,/g'
value,value,hello,hello,value,value
查看更多
一纸荒年 Trace。
4楼-- · 2020-07-18 03:04

What about this perl one-liner:

echo ',value,,,value,' | perl -pe 's/^(?=,)|(?<=,)(?=,|$)/hello/g'
# hello,value,hello,hello,value,hello
查看更多
登录 后发表回答