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:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop




![Unix Copy Command Examples [ cp command ]](http://s13.cyberciti.org/images/shared/rp/3/24.jpg)








{ 9 comments… read them below or add one }
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.
the sed command doesn’t work.
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:
This command doesn’t work. Why did you post this indicating that it is successful?
and it’s possible to replace string by ^m ? I need to replace all @ by carriage return.
Another way without using sed: tr -d ‘\r’ output; mv output input
I was saying: tr -d ‘\r’ \ output; mv output input seems the comment for doesn’t escape \<.
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 ;-)
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.