Luke Vanderfluit wrote:
Hi. I have a csv file that contains a field with a number, say 98.
I need to zerofill the fields to be 6 digits.
So any field that is say 98, should become 000098.

Is there an easy way to do this with search and replace?

Thanks.
Kind regards.


There are several ways to do it, depending in part on what exactly you want to do. I haven't tested the following but I think they will work:

- To fill in only the number under the cursor: no search-replace needed, place the Insert-mode cursor just before it and type in four zeros.

- To replace the number 98 (only) wherever it appears as a word (thus 98 but not 498 or 987 or 89 or 0098):

        :%s/\<98\>/000098/g

- To replace the number 98 wherever it appears between non-digits (thus also k98g or \x98 which the above wouldn't replace, but still not 0098 or x098):

        :%s/\%(^\|[^[:digit:]]\)98\_[^[:digit:]]/000098/g

- To fill-in all numbers to at least 6 digits:

        :%s/\<\d\{1,5}/=("00000" . submatch(0))[-6:]/g

- To fill or truncate all numbers to exactly 6 digits (losing the millions if there are any):

        :%s/\<\d\+\>/=("00000" . submatch(0))[-6:]/g

All this, assuming that existing numbers have no thousands separators and that you don't want to add any.

See
        :help :s
        :help /\<
        :help /\>
        :help /\d
        :help /multi
        :help [:digit:]
        :help sub-replace-expression
        :help submatch()
        :help expr-[:]
etc.


Best regards,
Tony.
--
Fortune's Real-Life Courtroom Quote #29:

THE JUDGE: Now, as we begin, I must ask you to banish all present
           information and prejudice from your minds, if you have
           any ...

Reply via email to