info home general windows unix linux debian mac os apache nginx iphone

Recent Articles

How to rename multiple files in Unix or Linux

Convert docx to doc in Mac OS X Snow Leopard or Leopard

HISTORY shell variable management in Unix/Linux

How to eject CD/DVD from your MacBook or iMac

Play Prince of Persia on Ubuntu Linux using DOSBox

Tags

How to remove CTRL M characters

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

Using emacs editor

Open trashnotes.txt in emacs and do this:

ALT+Xreplace-stringENTER CTRL+Q CTRL+MENTERENTER

Using vi editor

Open trashnotes.txt in vi. Then 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 \15\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";
}

Last Update: January 2009