Nick Vanderbilt
Nick Vanderbilt

Reputation: 38540

removing all trailing whitespaces

I want to remove all trailing white spaces from my .rb file. Also I want to remove all trailing ^M characters. This is what I have got. Does it look okay?

find . -name '*.rb' | xargs perl -pi -e 's/ +$//'

Upvotes: 1

Views: 1983

Answers (2)

anubhava
anubhava

Reputation: 786011

I think find + sed will do the job for you:

find . -name '*.rb' -exec sed -i.bak 's/\s*$//' {} \;

On Mac use this command since \s (a perl extension) is not recognized on Mac's sed:

find . -name '*.rb' -exec sed -i.bak 's/[ ^I^M]*$//' {} \;

-i is for inline editing
-i.bak is for keeping a backup of original with .bak extension.

Upvotes: 0

zellio
zellio

Reputation: 32524

If you want a regex for trailing whitespace use the \s meta character which stands for all whitespace characters

find . -name '*.rb' | xargs perl -pi -e 's/\s+$//'

If you want to maintain a line break then change the replacement term to something like

find . -name '*.rb' | xargs perl -pi -e 's/\s+$/\n/'

or

find . -name '*.rb' | xargs perl -pi -e 's/\s+$/\r\n/'

This will however mean that the lines now have trailing whitespace again.

Upvotes: 4

Related Questions