Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace spaces between letters only

Tags:

regex

vim

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/
like image 990
7mood7 Avatar asked May 28 '26 02:05

7mood7


2 Answers

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.

like image 123
Denys Séguret Avatar answered May 31 '26 09:05

Denys Séguret


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
like image 39
Randy Morris Avatar answered May 31 '26 10:05

Randy Morris