I have text file which shows ^M character when opened using less command in mac terminal. I tried using the below command to remove ^M character.
awk '{ gsub("\n", "\r"); print $0;}' input > output
cat input | tr ‘\n’ ‘\r’ > output
But none of them worked. Could someone help to fix this using some Linux commands.
What is this ^M? The ^M is a carriage-return character. If you see this, you're probably looking at a file that originated in the DOS/Windows world, where an end-of-line is marked by a carriage return/newline pair, whereas in the Unix world, end-of-line is marked by a single newline.
It is known as carriage return. If you're using vim you can enter insert mode and type CTRL - v CTRL - m . That ^M is the keyboard equivalent to \r.
To enter ^M, type CTRL-V, then CTRL-M i.e. hold down the CTRL key then press V and M in succession. where "RET" means and C-q and C-m mean . See Practical Guide to Linux Commands, Editors, and Shell Programming 3rd Edition by Mark G.
You can use sed
:
sed 's/^M// filename > newfilename
If you wish to use awk
then do:
awk '{sub(/^M/,"")}1' filename > newfilename
To enter ^M
, type CTRL-V
, then CTRL-M
. That is, hold down the CTRL key
then press V
and M
in succession.
Update
As suggested by @glenn jackman in comments, it is easy to use \r
then to get ^M
col < input > output
Or:
vim "+set ff=unix" "+saveas output" "+q" input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With