tags:

views:

86

answers:

4

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  A: 

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
Anders
Why the backslash before the + and ()?
Nils
Also I don't understand \1.0 \2.0 and \3.0 after the / could you explain it a bit?
Nils
It needs to be escaped. \1 \2 \3 are groupings. I simply add .0 those each one of those groups.
Anders
Yes just read it up again \1 \2 \3 are the references for the groups defined before..
Nils
+4  A: 

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.

paxdiablo
+1, Because this was a better regex then mine.
Anders
s/\([0-9]\+\) /\1.0 /g is shorter
Nils
but thx for the answer :)
Nils
+5  A: 

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.

Peter van der Heijden
This one is beautiful. One needs to admit that. You get a vote up from me.
Anders
A: 

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

Raghuram