Replacing Sequentially Empty Values ​​in a CSV File

I have a line of text like:

value,value,,,value,value 

I want two empty values ​​to be replaced with another value. Sort of:

 value,value,hello,hello,value,value 

I am currently trying something like:

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

Specifies empty values ​​at the beginning, at the end, and in the middle. BUT, it does not catch two consecutive empty values ​​in a line. How to update regular expression patterns so that an undefined number of consecutive empty values ​​is displayed in the middle?

+4
source share
3 answers

How about this one line perl:

 echo ',value,,,value,' | perl -pe 's/^(?=,)|(?<=,)(?=,|$)/hello/g' # hello,value,hello,hello,value,hello 
+3
source

I don’t think you can do this with a single substitution command, since Sed replaces the non-overlapping occurrences of your pattern. This ugly hack might work, but you need to prevent another character (I chose ";") in your values:

 $ echo 'value,value,,,value,value' | sed -r 's/,/,;/g;s/(^|;)(,|$)/\1hello\2/g;s/,;/,/g' value,value,hello,hello,value,value 
+2
source

Other pearl single-line:

 perl -we '$_=<>; while(s/,,/,hello,/) {}; print;' value.txt perl -we 'print join ",", map { $_ || 'hello' } split /,/, <>;' value.txt 
+1
source

All Articles