Convert DOS (or Windows) and Mac text files to Unix, or vice-verca

I tried to open windows text files in Mandriva, but there seems to be a problem with the end of line… How do I fix this?!

Figure 1: Start the KonsoleCommon problem! If you need to exchange text files between DOS/Windows, Mac, and Linux, be aware of the “end of line” problem. Under DOS, each line of text ends with CR/LF (that is, ASCII 13 + ASCII 10), with LF under Linux. If you edit a DOS text file under Linux, each line will likely end with a strange–looking `M' character; a Linux text file under DOS will appear as a kilometric single line with no paragraphs…

Most linux programs that I use do the correction automatically, but there might still be some old programs around that do not know how to deal with this… For instance, I noticed that it can be a problem with input files to a fortran program.

Same goes for windows, most programs will know how to deal with it, but you still find programs that get confused, and notepad is one of them.

Anyway, under Mandriva, the fix is easy! Simply install

unix2dos

and

dos2unix

When you want to convert a windows text file to unix, open a console (Figure 1), move into the proper directory, and type

dos2unix the_file_I_want_to_convert.txt

To convert a unix text file to windows, open a console, move into the proper directory, and type

unix2dos the_file_I_want_to_convert.txt

Actually, those programs are quite easy to write, usually a one liner in Perl! So while I'm at it, here they are…

This script will perform a conversion from unix to dos:

#!/usr/bin/perl -pi
s/\n/\r\n/; 

Save it as unix2dos.pl, make it executable (chmod a+x unix2dos.pl) and you're all set. Here is the code for dos2unix.pl

#!/usr/bin/perl -pi 
s/\r\n/\n/; 

And for those who have to deal with Macs, we have mac2unix.pl:

#!/usr/bin/perl -pi.unix
s/\r/\n/g; 

and unix2mac.pl:

#!/usr/bin/perl -pi.unix
s/\n/\r/g; 

Now, you should be all set with you text files!