Reputation: 3162
I am currently working on a script which processes csv files, and I am trying to make the script replace all blank fields in the csv file, with a string "data_n/a". Initially I had thought I could simply use the following to accomplish this task:
sed -e "s/hi/data_n\/a/g"
but unfortunately that would leave out any empty fields that could possibly occur at the beginning or the end of the lines of the csv file. I am not sure how to go about this, so I was wondering if anyone could help push me in the right direction or offer advice as to what I should do? thanks!
also here is a sample of the csv file:
,,6004,,,15:00.00,30004,Colleen,2010-02-10
2,Closed,6005,,,30:00.00,30005,Rich,2010-02-11
7,Closed,6001,,,30:00.00,10001,Mary Beth,2010-02-11
Upvotes: 1
Views: 3159
Reputation: 58371
This might work for you (GNU sed):
sed -r ':a;s/(^,)|(,)(,)|(,)$/\2\4data_n\/a\1\3/g;ta' file
Upvotes: 0
Reputation: 12138
If awk is an option, you can try the following:
awk -F, '{for(i=1;i<=NF;++i){if($i==""){printf "data_n/a"}else{printf $i} if(i<NF)printf ","} printf "\n"}' infile
Upvotes: 2
Reputation: 7802
the ^ indicates beginning of line and $ is end of the line
sed "s/,,/data_n\/a,/g;s/^,/data_n\/a,/;s/,$/,data_n\/a/" file >outfile
Upvotes: 0
Reputation: 63688
Using perl regex,
perl -pe 's;^,|,$|(?<=,),;data_n\/a,;g' input.cvs
Using sed,
$ sed -r 's;^,|,$;data_n\/a,;g
:l
s;,,;,data_n\/a,;g
t l' input.cvs
Upvotes: 3