Could I ask a follow-up question along these lines?
I've never used \=, but I see it only works at the beginning of the substitute
string and makes the entire replacement an expression. Is there a way to put it
in the middle.
For example, I was thinking if the CSV file had other numbers, and only one
field should be 0 padded, ex:
Blah, 745, blah, 98, blah
Blah, 34, blah, 200, blah
And only the 4th field should be zero padded, you'd want something like this:
%s/\(\([^,]\+,\s*\)\{4\}\)\(\d\{1,6\}/\1\=someExprWith\2/g
That's an eyesore, maybe not the best regex, but it'd work if you could put the
expr in the middle of the replace string. Is this doable?
*tim*
-----Original Message-----
From: A.J.Mechelynck [mailto:[EMAIL PROTECTED]
Sent: Wednesday, May 09, 2007 4:15 AM
To: Luke Vanderfluit
Cc: [email protected]
Subject: Re: replace number with zero-packed number
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 ...