Skip to content
Advertisement

Replace characters in specific columns only (CSV)

I have data like this:

1;2015-04-10;23:10:00;10.4.2015 23:10;8.9;1007.5;0.3;0.0;0;55
2;2015-04-10;23:20:00;10.4.2015 23:20;8.6;1007.8;0.4;0.0;0;56
3;2015-04-10;23:30:00;10.4.2015 23:30;8.5;1008.1;0.4;0.0;0;57

It has dot . as decimal separator but I need to use , instead.

Desired data:

1;2015-04-10;23:10:00;10.4.2015 23:10;8,9;1007,5;0,3;0,0;0;55

I tried using Sed. With sed -i 's/./,/g' myfile.csv I could replace all dots with commas but would destroy dates on the fourth column. How can I change dots to commas in elsewhere but leave the fourth column as it is? If some other Linux tool is better for this task than Sed I could use it as well.

Advertisement

Answer

sed is for simple substitutions, for anything else just use awk:

$ awk 'BEGIN{FS=OFS=";"} {for (i=5;i<=NF;i++) sub(/./,",",$i)} 1' file
1;2015-04-10;23:10:00;10.4.2015 23:10;8,9;1007,5;0,3;0,0;0;55
2;2015-04-10;23:20:00;10.4.2015 23:20;8,6;1007,8;0,4;0,0;0;56
3;2015-04-10;23:30:00;10.4.2015 23:30;8,5;1008,1;0,4;0,0;0;57
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement