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

我是研究僧i 提交于 2020-01-14 14:49:06

问题


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


回答1:


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.




回答2:


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.




回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/3332973/regex-find-and-replace-in-vim-adding-0-to-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!