usually in order to remove the ^M from file we do

dos2unix test.txt test.txt

tr -d '\r' < old.file > new.file

but this approach insist to create new file

if we do not want to create another file then the solution is: example of perl one liner

perl -pi -e 's/^M//g' file1

I tried it on Solaris but for unclear reasons, the ^M still exist in the file?

please advice what its wrong here

  • How are you typing ^M? It needs to be one single control character, not two characters ^ and M.
    – nanny
    Mar 16 '15 at 13:08
  • 1
    The perl command is creating a new file implicitly.
    – llua
    Mar 16 '15 at 13:08
  • On Solaris 11 you can use the GNU tools like gsed which has inline replacement.
    – Lambert
    Mar 19 '15 at 14:55

Perl needs a \r as well.

perl -pi -e 's/^M//g' file1
               ^^ - should be \r

Although actually, you probably just want to stick with line endings.

perl -pi -e 's,\r\n,\n,g' file1

Although actually - you don't need perl for this. sed is perfectly capable:

sed -i.bak -e 's,\r\n$,\n,g' file1
  • 1
    Solaris sed doesn't have a -i option and doesn't support \r and sed pattern space (any implementation) don't contain \n (you'd need s/^M$// where ^M would be a CR character). Mar 16 '15 at 15:09
  • 1
    what @StéphaneChazelas means at the end of his comment is that the ^M shown there is 1 (special) caracter, displayed as ^M in vi (or with cat -v), but entered with: ctrl + v ctrl + m Mar 16 '15 at 16:51

You need to use \r, not ^M to match carriage return characters. ^M has removed all M characters at the beginning of the line, so you may want to check your file is still OK...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.