Friday, April 13, 2012

How to Convert a file from Windows format to Linux format

This is a Perl implementation of "dos2unix" (a utility to convert Windows/DOS file format to Linux/UNIX file format.

#!/usr/bin/perl
use strict;

use File::Copy;
use File::Temp;

my $FILENAME = "MY_FILE.txt";

dos2ux($FILENAME);

sub dos2ux {
    my $infile = shift;
    my $is_converted = 0;

    # Make a temp file which will self delete automatically.
    my $tmp = File::Temp->new(
        UNLINK => 1);

    if (open(INFILE, $infile)) {
        if (open (OUTFILE, ">", $tmp->filename)) {
            binmode(OUTFILE);
            while () {
                s/\r\n$/\n/;
                print OUTFILE $_;
            }
            close(OUTFILE);
            $is_converted = 1;
        }

        close(INFILE);
    } else {
        print "Fail to open $infile\n";
    }

    if ($is_converted) {
        copy($tmp->filename, $infile);
    }
}

No comments:

Post a Comment