Reputation: 1403
I want to make a sed command to change strings that each comma separated part will be in double quotes. The problem is that some values have already double quotes.
Change from:
ABZ00016,ABZ,"449,9",450,445,449,"-0,21",405,13,"182,15",0,0,0
to
"ABZ00016","ABZ","449,9","450","445","449","-0,21","405","13","182,15","0","0","0"
I prepared two sed commands:
First command excludes values with double quotes
sed -e 's/"[^"]*"//g'
Second adds double quotes to each part
sed -e 's/\([^,]*\),/"\1",/g'
And now I wanted to exclude results from first command and make changes using second command:
sed -e '/"[^"]*"/!s/\([^,]*\),/"\1",/g'
But it doesn't work...
Upvotes: 0
Views: 971
Reputation: 58371
This might work for you (GNU sed):
sed -r 's/^/\n/;:a;s/\n$//;s/\n("[^"]*",?)/\1\n/;s/\n([^,]*)(,?)/"\1"\2\n/;ta' file
Introduce a newline as a marker then: remove the marker when all fields have been processed, skip over quoted fields and surround other fields with quotes. With each substitution advance the marker down the line.
Upvotes: 2
Reputation: 784958
Using gnu-awk
you can do this:
awk -v FPAT='"[^"]*"|[^,]*' -v OFS=, '{
for(i=1; i<=NF; i++) {
gsub(/^"|"$/, "", $i)
$i = "\"" $i "\""
}
} 1' file
Output:
"ABZ00016","ABZ","449,9","450","445","449","-0,21","405","13","182,15","0","0","0"
Upvotes: 2
Reputation: 128
Use sed with regex mate:
sed -r -e 's/[-.a-zA-Z0-9]+/"&"/g' -e 's/""/"/g'
Edit: Updated to Your request, works as expected:
sed -r -e 's/"([^,]+)(,)([0-9]+)"/\1\.\3/g' -e 's/[-.a-zA-Z0-9]+/"&"/g' -e 's/""/"/g' -e 's/\./,/g'
Upvotes: 1