How do I remove trailing whitespace across all open buffers and save only changed files?
Answer
:bufdo keeppatterns %s/\s\+$//e | update
Explanation
If you keep many files open during a refactor, cleaning trailing whitespace one buffer at a time is slow and error-prone. :bufdo lets you run one Ex pipeline across every listed buffer, while update writes only buffers that actually changed. This keeps the operation fast and avoids noisy writes.
How it works
:bufdoiterates through listed buffers and executes the following command in eachkeeppatternsprevents%sfrom overwriting your last search pattern (@/)%s/\s\+$//eremoves trailing whitespace on each line;esuppresses pattern-not-found errors in clean buffers| updatewrites only if the buffer was modified
Example
Use this after a broad multi-file edit where trailing spaces may have been introduced:
:bufdo keeppatterns %s/\s\+$//e | update
This applies cleanup to all open buffers and persists only actual diffs.
Tips
- Pair with
:args+:argdowhen you want explicit file scope instead of all open buffers - Run
:lsfirst if you want to confirm which buffers are listed before batch editing - If you want to skip special buffers, filter your working set first (for example by opening only target files before running
:bufdo)