If you’re moving a text file from Windows to Linux, and unless your ftp program has a method of converting the Windows text to Unix, the file will have a CONTROL-M (^M) character at the end of each line. In many cases, the control characters don’t hurt anything, because CONTROL-M, or carriage return, is treated as white space, and is ignored by many programs. However, some programs, such as the Perl interpreter, are adversely affected.
How can I get rid of those pesky Control-M characters at the end of each line in a file?
If you’re moving a text file from Windows to Linux, and unless your ftp program has a method of converting the Windows text to Unix, the file will have a CONTROL-M (^M) character at the end of each line. In many cases, the control characters don’t hurt anything, because CONTROL-M, or carriage return, is treated as white space, and is ignored by many programs. However, some programs, such as the Perl interpreter, are adversely affected.
You can remove CONTROL-M’s with the dos2unix utility. If it’s installed on your system, just type dos2unix -o oldfile_ name -n new_filename or dos2unix -k filename. The former command creates a new file; the latter replaces the original file with the newly converted file.
If dos2unix isn’t available, you can also use vi to fix this problem. Edit the file in vi and enter the command :%s/ ^M$//. The colon tells vi to allow you to enter an ex command; the percent sign indicates you want to perform the command on all lines of the file; and the substitute command, s///, replaces the text between the first and second slash with the text between the second and third slash. In our case, a ^M at the end of the line ($) is replaced with nothing.
For more about ex commands, see this month’s “Power Tools” column, page 34.
There is…
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: