7mood7
7mood7

Reputation: 51

Replace spaces between letters only

I have a file with columns of numbers and letters:

0.01182290 0.02526555 0.46794573 RING zinc finger protein putative 0105800 1076 1166 -90

I want to replace the spaces between the letters to underscores.

0.01182290 0.02526555 0.46794573 RING_zinc_finger_protein_putative 0105800 1076 1166 -90

Im new to regex, the substitute string is [a-zA-Z]\s[a-zA-Z], but I can't figure what the replacement is. Everything I tried changes the letters between the spaces.

:%s/[a-zA-Z]\s[a-zA-Z]/??/g/

Upvotes: 2

Views: 677

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382150

You can use this:

:%s/\v(\a)\s(\a)/\1_\2/g 

The idea here is to use capturing groups and put their captured value in the output.

Upvotes: 7

Randy Morris
Randy Morris

Reputation: 40927

A much simpler alternative would be to make use of vim's start of match and end of match atoms (\zs and \ze):

:%s/\a\zs\s\ze\a/_/g

Breakdown:

  • :%s/ - Start of the substitution command for the entire file
  • \a - Shorthand for [A-Za-z]
  • \zs - Start of match string
  • \s - Space or Tab
  • \ze - End of match string
  • \a - Same as above
  • /_/ - Replace the match string with an _
  • g - For each occurrence on the line

Upvotes: 5

Related Questions