Linux Commands

Remove Control M from File in Linux

The control M is called the Carriage-return, followed by the Line Feed or LF for indicating the new line. Sometimes, the control M option can cause issues while transferring files from Windows to Linux/Unix. In Linux, the ^M also leads to unexpected errors in the shell script and configures the files while editing them.

Therefore, it becomes hard to spot this issue, and users end up being confused. So, if you are also facing the same problem, this guide is for you. In this guide, we will cover the information about the ways to remove control M from a file in Linux.

How to Remove Control M from File in Linux

One of the best ways to find the ^M character is by using the cat command along with the -v option, as this will show you the non-printing characters. It is essential to add the -v command most of the time. Only the cat command does not show the ^M character in most of the editors by default. After running the cat -v command, all the carriage returns will be visible at the end of each line. So, let’s quickly checkout the ^M in a file by executing the following command in the terminal:

cat -v <filename>.txt

You can also use the vi command to check out the ^M availability in any text file. You only need to execute the following command:

vi -b <filename>.txt

Using the dos2unix command, this option easily converts your file into your desired format without changing multiple switches at the time. It is a useful command if you are stuck in situations like this:

dos2unix <filename>.txt

Using the grep command, the grep command is used to find a character or string in a file. Once the command runs, it displays all the ^M characters in the file. Then, Click Ctrl+V and Ctrl+M to write “^M”. Keep in mind that V has to be clicked first.

These commands will surely help you to remove the ^M character from your Linux file as these methods have already been tested and tried.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.