Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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 ' ' < 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; –  bdowning Feb 9 '13 at 12:32

2 Answers 2

up vote 6 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

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.