sed Delete / Remove ^M Carriage Return [ Line Feed ]

by on November 18, 2009 · 9 comments· last updated at November 18, 2010

How can I remove the ^M or ^M (carriage Return / line feed ) from text file using sed under UNIX or Linux operating systems?

Type the following command (to get ^M type CTRL+V followed by CTRL+M):

 
sed -e '/^M/d' input
sed -e '/^M/d' input > output
# gnu sed
sed -i -e '/^M/d' input
 

The substitute command can be used as follows too:

 
sed -e 's/^M//g' input
sed -e 's/^M//g' input > output
# gnu sed
sed -i -e 's/^M//g' input
# replace line feed with FOO
sed -i -e 's/^M/FOO/g' input
 


You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 9 comments… read them below or add one }

1 icedwater January 2, 2011 at 4:23 pm

On my version of sed, GNU sed 4.2.1, the above command sets perform quite differently:

sed ‘/^M/d’ input removes the lines with ^M in them, whereas
sed ‘s/^M//’ input removes just the ^M from the lines.

The latter was the desired behaviour in my case, I hope this helps.

Reply

2 Elizabeth July 9, 2012 at 5:41 am

the sed command doesn’t work.

Reply

3 fitorec July 13, 2012 at 12:24 am

In some cases I had to check that all files have no carriage return at the end of the line.

With the command “be” this task although it seems somewhat labored is greatly facilitated.

I leave here the statement that I use for this purpose:

#tested with GNU sed
sed -e '/^M/d' -i -r $(find . -type f)

Reply

4 MaindotC November 8, 2012 at 5:49 pm

This command doesn’t work. Why did you post this indicating that it is successful?

Reply

5 albatorv November 26, 2012 at 9:42 am

and it’s possible to replace string by ^m ? I need to replace all @ by carriage return.

Reply

6 Valentin February 8, 2013 at 2:02 pm

Another way without using sed: tr -d ‘\r’ output; mv output input

Reply

7 Valentin February 8, 2013 at 2:03 pm

I was saying: tr -d ‘\r’ \ output; mv output input seems the comment for doesn’t escape \<.

Reply

8 Werner February 13, 2013 at 1:20 pm

Hi
Try this example: sed “s/\^M//g” testfile >testfile.out.
It is important to put a Backslash to protect the ^M charactar!
cheers and have a nice day ;-)

Reply

9 bogus March 3, 2013 at 9:07 pm

For those of you saying this doesn’t work, I think I might have your answer. Please note this line in the article:

“Type the following command (to get ^M type CTRL+V followed by CTRL+M):”

You can’t just type the carat symbol and a capital M. You have to hit CTRL-V and then hit CTRL-M. I had quite a time figuring that out….but once you do it right, it works great.

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , , , , , , , , , , , ,

Previous Faq:

Next Faq: