3

I have textfiles with paths that have lost underscores between words inline in an OCR process. I want to keep the indentation and put back the underscores in the paths.

I have a path like this:

    /dir/file name and stuff

I want it to look like this:

    /dir/file_name_and_stuff

If I try:

:s/\s/_/g

I get:

____/dir/file_name_and_stuff

2 Answers 2

9

The substitution is easier to read with word-boundaries in my opinion, and very magic mode makes typing easier:

:%substitute/\v>\s+</_/g
2
  • Very cool. Shorter and easier to read. Thank you for that :) Nov 11, 2021 at 14:25
  • @RasmusGroth that's what upvotes are for :) see Voting up, though it looks like you don't quite have that privilege yet :(
    – D. Ben Knoble
    Nov 11, 2021 at 14:35
2

I found this answer posted by u/rewardit on Reddit which does the trick, but I didn't find anything on SO or networked sites so thought I would post it here as I prefer this format to Reddit

This will remove all single whitespaces

:s/\(\S\)\s\+/\1 /g

This will remove single whitespaces between words, but not multiple whitespaces at the end of the line:

:%s/\(\S\)\s\+\(\S\)/\1 \2/g
2
  • Welcome to Vi and Vim! Self-answering is allowed and encouraged, no need to call that out in the post :)
    – D. Ben Knoble
    Nov 11, 2021 at 14:23
  • Thanks @D.BenKnoble - and thanks for improving on the answer 🙏 Nov 11, 2021 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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