I want to find the most elegant way to replace every second space on each line with Vim. Most elegant solution accepted.

Example input

123 1234 1345 123456 12344567 12345678
123 1234 1345 123456 12344567 12345678 123 1234 1345 123456 12344567 12345678

Intended output

1231234 1345123456 1234456712345678
1231234 1345123456 1234456712345678 1231234 1345123456 1234456712345678

Assuming you want to remove all the odd-numbered spaces:

:s/\v (\S*( |$))/\1/g
  • with magic (\v) to reduce the escaping needed
  • matches space followed by (non-whitespace (\S*) followed by (another space or end-of-line))
  • and replaces it with the matched part after the leading space

For each space matched at the start of the regex, the next space is eaten by the regex match and can't be part of another match. So this only affects the odd-numbered spaces.

A solution candidate with a regular expression and with the magic directive is

:.s@\v(\d+) (\d+)@\1\2 @g

where matching numbers in the groups. It can be improved with

:.s@\v([^ ]+) ([^ ]+)@\1\2 @g

so matching everything else except spaces in the groups.

Example

Input

1 2 3 4 5 6 7 8 9 10

Its Output

12  34  56  78  910

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.