Nils
Nils

Reputation: 13777

Regex find-and-replace in vim: Adding .0 to numbers

I have a file which looks like below.

1   1  0  #  1 
6   1  0  #  2 
8   1  0  #  3 
10  1  0  #  4 
12  1  0  #  6 

How can I add .0 to all numbers, except the numbers behind the #. I think this should not be too difficult to do with a regular expression, but my regex knowledge is too rusty..

Upvotes: 3

Views: 9573

Answers (4)

paxdiablo
paxdiablo

Reputation: 882766

If your numbers after the # don't have spaces after them, you can use:

:g/\([0-9]\+\) /s//\1.0 /g

The use of () creates groups which you can refer to as \D in the replacement text, where D is the position of the group within the search string. This will give you:

1.0   1.0  0.0  #  1
6.0   1.0  0.0  #  2
8.0   1.0  0.0  #  3
10.0  1.0  0.0  #  4
12.0  1.0  0.0  #  6

If they do have spaces after them (which yours seem to have), you'll get:

1.0   1.0  0.0  #  1.0
6.0   1.0  0.0  #  2.0
8.0   1.0  0.0  #  3.0
10.0  1.0  0.0  #  4.0
12.0  1.0  0.0  #  6.0

in which case you can then do:

:g/\.0\(  *\)$/s//\1/g

to fix it up.

Upvotes: 7

Raghuram
Raghuram

Reputation: 3967

you can try this also sed 's/[0-9]/&.0/g' | sed 's/.0[ ]*$//g'

First sed add .0 all numbers and second one removes the trailing .0

Upvotes: 0

Anders
Anders

Reputation: 6218

Assuming it's well formed, using sed this should work.

EDIT: Just to clarify, vim was not attached as a tag to this questions when i saw it.

sed 's/\([0-9]\+\) \+\([0-9]\+\) \+\([0-9]\+\)/\1.0 \2.0 \3.0/' file

Upvotes: 1

heijp06
heijp06

Reputation: 11808

With VIM:

:%s/\v(#.*)@<!\d+/&.0/g

Explanation: \v = very magic (see help \v), @<! Matches with zero width if the preceding atom does NOT match just before what follows (see help \@<!). The rest of the pattern replaces strings of 1 or more digits with the same string followed by .0.

Upvotes: 9

Related Questions