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

Hi I am using the following command: perl -e 's/MIT/BERKELEY/i' -p -i.bat *.txt The problem is that if I have a file called test.txt, after executing this command, I have a ^M character appended to the end of all the lines in that file. Is there a way to prevent this.
  • Comment on ^M gets added to the end of the line while replacing strings

Replies are listed 'Best First'.
Re: ^M gets added to the end of the line while replacing strings
by sauoq (Abbot) on Jul 07, 2003 at 23:56 UTC

    That ^M is a carriage return. The one-liner you gave won't add them. What system are you working on and what system did the file originate on?

    -sauoq
    "My two cents aren't worth a dime.";
    
      I am working on a RED-HAT 7.3 and the file originated on a windows 2000 system. But before I executed the command I opened the file on a vi editor and did not see any ^M characters. Also I just now tried to create a new file using vi editor and then tried the same command. Now I did not see any ^M characters. So you are right, the one-liner is fine. So maybe it has got something to do with the file being originated in wondows. Thanks for your help.
        So maybe it has got something to do with the file being originated in wondows.

        Yes, it has everything to do with that.

        The dos2unix utility is your friend.

        You can fix it with perl too using a command like like:

        perl -i.bak -pe 's/\r\n/\n/' file.txt

        BTW, vi tries to be smart about whether it displays those ^M characters... which is probably why you didn't see them the first go around.

        -sauoq
        "My two cents aren't worth a dime.";
        

        'vi' on linux is actually vim, and it "helps" by dealing with ^M characters transparently.

        To have vim show them with the ^M display you're used to, use vim -C name_of_win_file.

        --Bob Niederman, http://bob-n.com