Remove an Invalid Character

The ^M character is the carriage return character, and is the "CR" part of the CRLF line ending scheme used by Windows systems. A Linux system might encounter this when a file was created on a Windows computer and then transferred.

This task can be trivially completed using the sed command. In most Linux shells (including bash), control-V will allow you to enter control characters by following it with the control-key combination used to render it. In this case, pressing C-v C-m (control-V followed by control-M) will insert a ^M token on the command line that will be replaced with the carriage return character when the command is run. It doesn't actually insert that character directly, as that would cause the cursor to return to the beginning of the line, which is obviously undesireable.

The command to run is this:

sed -i 's/^M//g' /path/to/file

where ^M is the token inserted as stated above, rather than the literal characters ^ and M.

Another option would be to use \\r, the more traditional escape sequence for the carriage return character. However, escape sequences like this do not work in single-quoted strings in Bash, so to use this, you'd have to do the following instead:

sed -i "s/\\r//g /path/to/file

I tend to avoid using double-quoted strings for sed commands, as generally you'd want the \\ chracter available for regex tokens, and having to escape it every time you use it is annoying, hence why I'd prefer the first command in this circumstance.