http://www.perlmonks.org?node_id=877149


in reply to A 'strange' character("^M") of contrasting color appearing unexpededly at the end of lines of a unix file. How can it be removed?

I recently ran into this same issue. I wrote the following short script to fix it. I don't know if it will work with everything, but it has for everything I have given it. Just supply the info it asks for, and it will create the FIXED file for you.

#!/usr/bin/perl -w use strict; use warnings; my $FILE; my $DST; my $filename; print("What file do you want to remove the trailing Carrige Returns fr +om:"); while($filename=<STDIN>){ chomp($filename); last; } open (FILE, '<', $filename) or die "Failed to open file:$!"; open (DST, '>', "FIXED".$filename) or die "Failed to open fix file:$!" +; while (<FILE>){ if($_ =~ /\r$/){ s/\r//; print DST $_; } else{ print DST $_; } } print("The file $filename has been fixed. The new file name is FIXED". +$filename.".\n"); close FILE;

I am sure there are improvements that could be made, but it was a nice study on input output and basic regex.

I found that the ^M is indeed the same as a \r as is mentioned a couple of times above. This script just replaces it with nothing, essentially deleting it.

Cheers.
  • Comment on Re: A 'strange' character("^M") of contrasting color appearing unexpededly at the end of lines of a unix file. How can it be removed?
  • Download Code

Replies are listed 'Best First'.
Re^2: A 'strange' character("^M") of contrasting color appearing unexpededly at the end of lines of a unix file. How can it be removed?
by AR (Friar) on Dec 14, 2010 at 21:28 UTC

    You may have an intention error in your while(<FILE>) loop. Right now, you're testing if the string ends with a \r and then you're removing the first occurrence of it. If your string is "Hello \rthere\r\n", your code would print "Hello there\r\n" to DST.

    If I understand your intention correctly, I would replace the while loop with the following:

    while (<FILE>){ s/\r$//; print DST $_; }

    If you want to get rid of all occurrences of \r in the line, you could just say:

    while (<FILE>){ s/\r//g; print DST $_; }
Re^2: A 'strange' character("^M") of contrasting color appearing unexpededly at the end of lines of a unix file. How can it be removed?
by TechFly (Scribe) on Dec 14, 2010 at 20:15 UTC
    Heh, now that I look at it there, I notice that I neglected to close DST too. Oops.