How to remove CTRL M characters

Published on January 01, 2009

If you copy a file created or modified in Windows or DOS to a Linux/Unix file system, you sometimes find ^M characters at the end of each line.

Here are steps to remove the ^M characters from a file called trashnotes.txt.

RANDOM NOTES
1. Put trash in the trash can.
2. Close the lid.
3. Take the trash can outside.
LINES

dos2unix

Using the utility dos2unix you can get rid of the ^M.

dos2unix trashnotes.txt

When you run that command, trashnotes.txt will be stripped of its ^M characters.

On some computers that doesn't work, so you can do something like this: dos2unix trashnotes.txt > trashnotes2.txt

Remove Ctrl+M using emacs editor

Open trashnotes.txt in emacs and do this:

ALT+Xreplace-stringENTER CTRL+Q CTRL+MENTERENTER

Remove Ctrl+M using vi editor

Open trashnotes.txt in vi and do this:

ESC:%s/^M//g

You get the above ^M by pressing Ctrl V followed by Ctrl M

Adding ^M to end of lines in file

For some weird reason, if you want to add ^M, add the code \r\n to the end of the line.

Here's a Perl script that demonstrates it.

#!/usr/bin/perl
use strict;
my $lines = << LINES;
RANDOM NOTES
1. Put trash in the trash can.
2. Close the lid.
3. Take the trash can outside.
LINES

foreach (split/\n/, $lines) {
    print;
    print "\15\r\n";
}

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Published on January 01, 2009