Last Updated: February 25, 2016
·
1.669K
· kormie

Remove all whitespace from a directory

Hate it when people commit whitespace in a codebase? Why not kill it all? There's definitely a way to do this with sed(1) but this is my preferred workflow.

First, find all files inside your current directory:

find . -type f
#We don't care about directories

Then turn that output into a single line, space delimited list

find . -type f  | tr "\\n" " " 
#Turn all newline characters into a space

Now we have a list of files we can pipe into vi(m)

find . -type f  | tr "\\n" " " | xargs vim
#Start vim with the arglist populated with all of our files

Once vim loads, you can run a command over all the files you just gave it with:

:argdo

In our case, we want to remove trailing whitespace from each document:

:argdo %s/\s\+$//

Since we want to save the changes we've made we can also tell vim to write these files:

:argdo %s/\s\+$// | w

I also don't care about the files where no trailing whitespace was found, I pass it the "e" flag

:argdo %s/\s\+$//e | w
#See :help :s_flags for more info

Finally, If you don't care which files were changed you can call silent before the command

:silent argdo %s/\s\+$//e | w

I hope this helps someone!

4 Responses
Add your response

Just what I was looking for, thanks! For others looking to do this on a single file type:

find * -iname '*.cs'  -type f |  tr "\\n" " " | xargs vim
over 1 year ago ·
:silent argdo %s/\s+$//e | w

this is broken it removes plus characters (+) from the end of a line when there is whitespace before the plus but not after it.

it should be:

:silent argdo %s/\s\+$//e | w
over 1 year ago ·

thanks @gerst20051, it was typed correctly in all but the last instance :P

over 1 year ago ·

@kormie another issue I see is that this will fail for paths with spaces and it also messes up the terminal after you close vim. to fix both of these issues you should change the code to the following.

find -E . -type f -iregex ".*\.(java|js|php)$" | tr "\n" "\000" | xargs -o0 vi
over 1 year ago ·