Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm sooo fed up with useless spaces in source files that I've even configured vim to show them.

The problem is that I'm very often (if not always) have to deal with useless spaces with my mates developpers.

I'd just like to scan source files (given a regular expression) and remove whitespaces from all given files.

I've search around the web ("bash remove whitespace" etc.) but did not find something useful.

share|improve this question
Remove what whitespace? Without an example of what you want removed, I don't see how anyone could help you. (I'm guessing tr -d ' ' < file.foo isn't exactly what you're looking for.) – Mat Feb 9 '13 at 12:28
How can you programmatically tell the difference between useless whitespace and useful whitespace? BTW: You could use a for loop and mv and sed and collapse whitespace; – bsd Feb 9 '13 at 12:32
You can also remove trailing whitespace when you save your files in vim (saving you the trouble to rerun this command after you edit something): unix.stackexchange.com/questions/75430/… – Lucas Apr 27 at 9:03
up vote 7 down vote accepted

If by useless whitespace you mean trailing whitespace at the end of the line, this will work on GNU systems:

find -name '*.c' -print0 | xargs -r0 sed -e 's/[[:blank:]]\+$//' -i

(replace *.c with whatever your source files match)

share|improve this answer
I've changed the title, thank you very much for your answer. Someone has voted down because, maybe he thought it was soo simple, that no one should ask such question ;^). Thank you again. – Olivier Pons Feb 10 '13 at 20:14

This is a recurrent problem!

perl -i -pe 's/\s+\n/\n/'   *.c

(this also removes '\r\n')

I normally use a slightly more complex version "nrs" (no redundant spaces):

#!/usr/bin/perl -pi
s/\h*(\r\n|\n|\r)/\n/g;                 ## normalize \n (DOS, MAC)
s/^(\xFF\xFE|\xFE\xFF|\xEF\xBB\xBF)//;  ## remove BOM !

install it: chmod 755 nrs; cp nrs ~/bin; (or similar)

and use: nrs *.c

Don't use it in binary files!

share|improve this answer

Try Ex-way:

ex +'bufdo!%s/\s\+$//e' -scxa *.*

to remove trailing whitespaces from all files in the current folder. For recursion (bash4/zsh) you may use extended globbing (**/*.*).

Note: The :bufdo command is not POSIX.

share|improve this answer
note bufdo is not POSIX pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html – Steven Penny Apr 17 at 0:43

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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