Thursday, 19 February 2009

Removing trailing whitespace & tabs, at the end of lines in source code files.

I always edit files in Vim with highlighting of tabs and spaces at the end of lines, in case I catch myself putting them in, by adding these lines to my ~/.vimrc :

  let c_space_errors=1
  highlight WhitespaceEOL ctermbg=red guibg=red
  match WhitespaceEOL /[\s\t]+$/

But occasionally, I encounter a file that is caked in red squares and lines at the end of most lines, and a neat way of removing these in one go is to run the following command on the file (entered in command mode, after the ':' prompt:

  %s/[\ \t]*$//

Even more rarely, I get an entire directory of such files and need to blatt all the trailing whitespace. I either use this line directly from the command line (bash), or place it in a quick script to do the job:

sed 's/[\ \t]*$//' file1.c > file2.c

No comments: