Tuesday, August 16, 2011

How to remove ^M from file using VI

Sometimes DOS files have "^M" at the end of each line, which causes problem for perl to read lines correctly.
We can use VI to remove these annoying ^M.

=============Using VI================

Type the following command at the terminal.

vi file_name.txt


Basically vi is the name of a text editor under linux/mac.
After issuing this command, you should be able to see the command window showing the content of the file.

Next step is to remove the annoying ^M at the end of each line.
Type the following command in VI editor. Do not miss the semi-colon at the begining.

:%s/[ctrlkey+v and ctrl-key+M]/\r/g

You should be able to see the following at the left-bottom corner of the command window:
:%s/^V^M/\r/g

The command above is meant to replace ^M with a new line symbol "\n".

Press enter and wait for a while for every occurrence of ^M to be replaced.
Depending on the size of your file, it can take a while and the screen appears frozen.
When the replacing is done, type the following command to save and exit from VI.

:x

Good luck!

No comments:

Post a Comment