13

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.

Olivier Pons
  • 473
  • 2
  • 4
  • 16
  • 2
    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 09 '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 09 '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): http://unix.stackexchange.com/questions/75430/how-to-automatically-strip-trailing-spaces-on-save-in-vi-and-vim – Lucas Apr 27 '16 at 09:03

4 Answers4

12

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)

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Dennis Kaarsemaker
  • 8,420
  • 3
  • 29
  • 31
  • 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
1

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!

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
JJoao
  • 11,887
  • 1
  • 22
  • 44
0

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 a new globbing option (**/*.*).

Note: The :bufdo command is not POSIX.

kenorb
  • 20,250
  • 14
  • 140
  • 164
  • note bufdo is not POSIX http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html – Zombo Apr 17 '16 at 00:43
0

To avoid touching files that are already OK, with GNU tools:

grep -rlZ --binary-files=without-match --include='*.c' '\s$' . |
  xargs -r0 sed -i 's/\s+$//'
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501