Re: [SCRIPT] chomp: trim trailing whitespace

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]


Jeff Garzik wrote:

Attached to this email is, a Perl script which removes trailing whitespace from several files. I've had this for years, as trailing whitespace is one of my pet peeves.

Now that git-applymbox complains loudly whenever a patch adds trailing whitespace, I figured this script may be useful to others.

This is the script I use for the same purpose. It's a bit more sophisticated, in that it detects and avoids binary files, and doesn't throw an error if it encounters a directory (which can happen if you give it a wildcard.)

# Clean a text file of stealth whitespace

use bytes;

$name = 'cleanfile';

foreach $f ( @ARGV ) {
    print STDERR "$name: $f\n";

    if (! -f $f) {
	print STDERR "$f: not a file\n";
    if (!open(FILE, '+<', $f)) {
	print STDERR "$name: Cannot open file: $f: $!\n";

    binmode FILE;

    # First, verify that it is not a binary file
    $is_binary = 0;

    while (read(FILE, $data, 65536) > 0) {
	if ($data =~ /\0/) {
	    $is_binary = 1;

    if ($is_binary) {
	print STDERR "$name: $f: binary file\n";

    seek(FILE, 0, 0);

    @blanks = ();
    @lines  = ();

    while ( defined($line = <FILE>) ) {
	$line =~ s/[ \t\r\n]*$/\n/;

	if ( $line eq "\n" ) {
	    push(@blanks, $line);
	} else {
	    push(@lines, @blanks);
	    push(@lines, $line);
	    @blanks = ();

    # Any blanks at the end of the file are discarded

    seek(FILE, 0, 0);
    print FILE @lines;

    if ( !defined($where = tell(FILE)) ||
	 !truncate(FILE, $where) ) {
	die "$name: Failed to truncate modified file: $f: $!\n";

[Index of Archives]     [Kernel Newbies]     [Netfilter]     [Bugtraq]     [Photo]     [Stuff]     [Gimp]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Video 4 Linux]     [Linux for the blind]     [Linux Resources]
  Powered by Linux