box.matto.nl

home/

Replace decimal point by a comma with vi

Last edited

Substitute a decimal point by a comma in CSV file

When importing a text file like a CSV file into a spreadsheet program, the international settings can lead to a problem. In some countries the decimal mark is a point, in other countries it is a comma.

When the CSV file contains a decimal point as the decimal mark and the spreadsheet program only understands a comma as the decimal mark you will have to convert the file before importing it.

With the magic of regular expressions it is a piece of cake to solve this little annoyance.

Use vi to replace a decimal point by a decimal comma

Vi converts your file very fast

With vi it is easy to turn the decimal point into a decimal comma.

Replace first occurence of a decimal point on one line

This can be done with the following command.

First, move the cursor onto the line where you want to have the substitution. Then issue the command:

:s/\([0-9]\)\.\([0-9]\)/\1,\2/

Explanation:

  • :s : replace on this line
  • [0-9] : digit
  • \. : escaped period (point)
  • \( ... \) : searchpattern to match
  • \1 first matching item
  • \2 second matching item

So the whole line means: replace on this line a digit followed by a point followed by a digit by the digit before the point followed by a comma followed by the digit after the point.

We need to escape the point (.) with a backslash to prevent that it is seen as a wild-card.

Replace all occurences of a decimal point on one line

This, now off course is easy:

:s/\([0-9]\)\.\([0-9]\)/\1,\2/g

Replace first occurence of a decimal point on every line

:%s/\([0-9]\)\.\([0-9]\)/\1,\2/

With the % character we tell vi to substitute on all lines.

Replace all occurences of a decimal point on every line

This, now off course is easy:

:%s/\([0-9]\)\.\([0-9]\)/\1,\2/g

Replace decimal comma with decimal point

We can use the same mechanism the reverse way.

:%s/\([0-9]\),\([0-9]\)/\1.\2/g

In this case we use the decimal point not as searchpattern to search for but as the substition pattern, so there is no need to escape it.

Use your preferred vi implementation

As allways, the little Unix tools of the good old days are the most efficient in solving issues like these.

The above magic is standard ex magic so it works in vi and every vi clone. So if your preffered vi clone is vim, you can use vim, the commands will work there too.