Remove the ^M from a Linux file

Suppose that you are both using Windows and Unix systems.
You will have notice that when you create a file on Linux, Windows will open it as a text file in a single line.
Viceversa, creating a file on Windows and sending it to Linux will result that the file will contain strange characters, ^M.

Here, on Linux, how to replace the ^M with Linux’s Carriage Return and Line Feed.

CR = \r = Carriage Return
LF = \n = Line Feed

In DOS, all lines end with a CR/LF combination or \r\n.
In UNIX, all lines end with a single LF or \n.

The ^M is actually a CR or \r.

For determining what actual characters are in a file:

od -c filename.txt

Or just want to see the ^M notation:

cat -v filename.txt

To remove the ^M characters:

sed -e "s/^M//" filename > newfilename

CTRL+V and CTRL+M (keep holding CTRL) will generate the ^M

I faced this problem using a Linux application that won’t properly recognize Windows file because of this.

I you want to automate the process for replacing all the ^M in a file and make a backup of the same file before the changes:

OUT=$(basename $1)
sed -i.bak 's/^M//g' $OUT

Call it with the path of the file as argument if you are in another directory:

./ /path/to/file/myfile.txt

And the new file will be created in your current folder (unless differently specified in the script).