Rook
Rook

Reputation: 62558

Matching only a <tab> that is between two numbers

How to match a tab only when it is between two numbers?

Sample script

209.65834   27.23204908
119.37987   15.03317082
74.240635   8.30561924
29.1014 0

931.8861    -100.00000
-16.03784   -8.30562
;   
_mirror 
l   

;   
29.1014 0
1028.10 0.00
n   
_spline 
935.4875    250
924.2026913 269.8820375
912.9178825 277.4506484
890.348265  287.3181854

(in the above script, the tabs are between the numbers, not the spaces) (blank lines are significant; there is nothing in them, but I can't lose them)

I wish to get a "," between the numbers. Tried with :%s/\t/\,/ but that will touch the empty lines too, and the end of lines.

Upvotes: 1

Views: 1285

Answers (3)

alvin
alvin

Reputation: 1196

try

:%s/\([0-9]\)\t\([0-9]\)/\1,\2/g

explanation - search the patten <digit>\t<digit> and remember the part that matches <digit> .
\( ... \) captures and remembers the part that matches.
\1 recalls the first captured digit, \2 the second captured digit.

so if the match was on 123\t789, <digit>,<digit> matches 3\t7
the 3 and 7 are rememberd as \1 and \2

or

:g/[0-9]/    s/\t/,/g

explanation - filter all lines with a digit, then substitute tabs with a comma on those lines

Upvotes: 1

Mat
Mat

Reputation: 206851

Try this:

:%s/\(\d\)\t\(-\?\d\)/\1,\2/

\d matches any digit. -? means "an optional -. The pair of (escaped) parenthesis capture the match, and \1 refers to the first captured match, \2 refers to the second.

Upvotes: 4

google://vim+regex -> http://vimregex.com/ ->

:%s/\([0-9]\)\t\([0-9]\)/\1,\2/gc

You have 2 groups of numbers here ([0-9]) and tab-symbols \t between them. Add some escape symbols and you have the answer. g for multichange in single line, c for some asking. \1 and \2 are matching groups (numbers in your case).

It's not really hard to find answer for questions like that by yourself.

Upvotes: 1

Related Questions