Convert a file from Windows to Unix line endings

A neat little trick I learnt many years ago continues to come in handy now and again. Like yesterday at work. Someone had a file with Windows line endings and needed it converted to Unix line endings, otherwise the recipient couldn’t cope. Yeah, the recipient is clearly incapable, but there you go. There’s clearly many ways to do this, but the quickest way I know to convert the file is:

perl -pi.bak -e "s/\r\n/\n/g" /tmp/filename

Obviously, that last parameter is where you would put your filename.

Anyway, all this does is run a Perl regular expression on your file, and converts \r\n to \n. It also takes a backup of your file, just in case. And that’s it.

If you want to see the result for yourself, run od -c on the before and after files, and you should be able to see the different line endings quite clearly.

Leave a Reply