Remove CTRL-M (^M) characters from a file

Remove CTRL-M (^M) characters from a file

There are many occasions where we get a file from MS-DOS and do not trasfer them in ASCII mode or plain text mode.

What results is in several CTRL-M (^M) characters in a file at the end of the line. Removing them from small files is a simple task.

But what happens when the file has several different lines. Manually removing these characters can be tedious and not so pleasing task.

The following are the two preferred methods I would recommend to be done.

Remove CTRL-M (^M) characters from a file – using VI or VIM

The easiest I would use is vi or vim.

Just edit the file where you want the modifications to be made. Enter into the command mode or ESC mode (whichever you prefer to call it) by pressing ESC key.

Type in the following:

:%s/^M//g

To enter ^M, you will have to type CTRL-V and then CTRL-M. Meaning on your keyboard hold down CTRL key and then press V and then M (without leaving CTRL).

The above vi command will replace all the occurences of ^M with NULL or blank character.

Remove CTRL-M (^M) characters from a file – using SED

Or you can use the stream editor sed.

On the command line enter the following command>

sed -e "s/^M//" /path/to/file > /new/copy/for/file

To enter ^M, you will have to type CTRL-V and then CTRL-M. Meaning on your keyboard hold down CTRL key and then press V and then M (without leaving CTRL).

Remove CTRL-M (^M) characters from a file

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.