Removing ^M characters in VI

When porting a text file from Windows to UNIX you will quite often get a ^M on the end of every line. Apart from look bad and make it hard to read, if you text file happens to be a script, then this can also effect the way your script is run.

To remove the ^M characters at the end of all lines in vi, use this command.

:%s/^V^M//g

To get the ^V you need to type Control+V and Control+M for the ^M. However when you type this, it will appear on the screen like this:

:%s/^M//g

In UNIX, you can escape a control character by preceding it with a Control+V.

The %s command is the VI search command, here’s how it works.

:%s/old_string/new_string/g
old_string is the the string you want to replace
new_string is the new string you want to replace the old string with
g to make the changes globally through the whole document.

For some more tips on using VI have a look at my 10 Usefull VI tips post

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s