afshinbozorg has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to convert some file from Dos format to Unix format. On a windows machine This is perl, v5.10.1 built for MSWin32-x86-multi-thread I have tried
s/\015\012/\012/g s/\015/\013/\013/g s/\r\n/\n/g
but the file I am writing to is coming with ^M char ?
#! perl -w # Convert a dos format file to Unix removing ^M Char from file my $FileOpen = $ARGV[0]; my $FileTemp = "$FileOpen.Temp9687"; open(OPEN,"$FileOpen") || die "\nCan not open file $FileOpen $!\n"; open(CONV,">$FileTemp") || die "\nCan not write to file $FileTemp $!\n +"; foreach(<OPEN>){ $_ =~ s/\r\n/n/g; # $_ =~ s/\015\012/\012/g; # $_ =~ s/\015\013/\013/g; # $_ =~ s/\015//g; print CONV $_; } close(OPEN); close(CONV);

Replies are listed 'Best First'.
Re: Removing ^M char AKA dos2unix
by BrowserUk (Patriarch) on Feb 25, 2010 at 21:57 UTC

    This does the trick:

    perl -e"BEGIN{ binmode STDOUT }" -pe1 file.in > file.out

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      I like yours better, (and will probably use that from now on) - but this is what I normally do:

      perl -p -i -e 's/\r\n/\n/g' file1 file2 ... filen
        perl -MExtUtils::Command -e dos2unix file1 file2 dir1
        Or better still, install dos2unix utility
Re: Removing ^M char AKA dos2unix
by jwkrahn (Abbot) on Feb 25, 2010 at 21:49 UTC

    \r\n in the file is converted to \n in perl when you open the files in "text" mode so you have to use "binary" mode:

    #! perl -w # Convert a dos format file to Unix removing ^M Char from file my $FileOpen = $ARGV[ 0 ]; my $FileTemp = "$FileOpen.Temp9687"; open OPEN, '<:raw', $FileOpen or die "\nCan not open file $FileOpen $! +\n"; open CONV, '>:raw', $FileTemp or die "\nCan not open file $FileTemp $! +\n"; local ( $/, $\ ) = ( "\r\n", "\n" ); print CONV while <OPEN>; close OPEN; close CONV;
Re: Removing ^M char AKA dos2unix
by astroboy (Chaplain) on Feb 26, 2010 at 02:23 UTC
Re: Removing ^M char AKA dos2unix
by Anonymous Monk on Feb 25, 2010 at 22:42 UTC
Re: Removing ^M char AKA dos2unix
by jdrago999 (Pilgrim) on Feb 26, 2010 at 20:14 UTC

    afshinbozorg - please use the <code></code> tags around your Perl snippets - that way they will appear formatted correctly :-)

      My apology for responding late

      Thank you so much for all the wonderful reply. I love Perl community, I believe it poses the best of the best, as technical or human touch.

      Yes the binmode did the trick and in the process I learn many new trick. Thank you for all the great respond

      Cheers,

      Afshin