开发者

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

开发者 https://www.devze.com 2023-01-09 01:10 出处:网络
I have a file which looks like below. 110#1 610#2 810#3 1010#4 12 开发者_开发百科 10#6 How can I add .0 to all numbers, except the numbers behind the #. I think this should not be too difficul

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..


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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消