Fixing Carriage Return/New Line Problems

Sometimes if I open a text file in vi, the text shows up like this:

Title,Firstname,Lastname^MDr.,George,Washginton^MMr. ,John,Adams^MSenor,Thomas,Jefferson^MMr.,James,Monroe^MSenator,James,Madison^MSir,John Q,Adams

Those ^M characters should actually be returns. To fix this, run:

:%s/^M/\r/g

The ^M in the command above is actually typed by pressing Control-V, Control-M.

After running the command, the text file looks as it should.

Title,Firstname,Lastname
Dr.,George,Washginton
Mr. ,John,Adams
Senor,Thomas,Jefferson
Mr.,James,Monroe
Senator,James,Madison
Sir,John Q,Adams

If I don’t want to open the file in vi to fix it, I can fix it on the command line with:

$ tr '\r' '\n' < test.csv > x