3

My goal is to get rid of "bad" CRs and trailing spaces at once, so I am executing the following command:

:%s/^M\|\s\+$//g

The problem is that if at the end of the line there is a ^M and trailing spaces, only the ^M is removed.

Is there a way to replace both parts of the OR expression on the same time?

2
  • John, I felt the question's title sounded a bit too general so I took the liberty and changed it. Feel free to edit and change to something you like better.
    – Friedrich
    Oct 29, 2023 at 17:42
  • Do you still have something open in your question? How can we help you further? If one of the solution solves your problem maybe could you accept it using the v button next to the arrow voting buttons. It allow the question to rest :-) Oct 31, 2023 at 6:28

2 Answers 2

0

I would do:

:%s/\s*^M\?$//g

Where:

  • \? is for optional
  • ^M is inserted using Ctrl vEnter
2
  • 1
    Wait a second... without the $ in the pattern, you'll remove all whitespace anywhere or am I missing something?
    – Friedrich
    Oct 29, 2023 at 17:35
  • 1
    Thanks @Friedrich, well done :-) I have corrected the answer. Oct 29, 2023 at 18:24
0

I've had an autocmd that clears trailing white spaces on write, for a long time now in my ~/.vimrc

autocmd BufWritePre * :%s/\s\+$//e

This might kill your carriage return problem, if not you could try:

autocmd BufWritePre * g/[^"]\n/join

I've had the first autocommand for a long time and it works well.

The second one I've not tested.

2
  • 1
    Having an autocommand like this is a good idea. You might want to restrict based on filetype, though. Some formats (e.g. markdown) give trailing whitespace a meaning.
    – Friedrich
    Oct 30, 2023 at 20:43
  • of course, didn't think of markdown
    – Nickotine
    Oct 31, 2023 at 15:11

Your Answer

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

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