Skip to main content

Solution: Converting Line Breaks In Linux

Posted on October 6, 2012 by pineheadpinehead

Linux text files and Windows text files differ from each other in an important aspect. They have a different way to indicate the end of a line. Sometimes, when opening a text file on Linux, you see a ^M here and there. This means that the text file contains Windows-like line breaks. This solution describes how to convert a Windows-like text file to a Linux-like one, and the other way around.
To convert a text file with Windows-like line breaks to a one with Linux-like line breaks:

[rechosen@localhost linebreaks]$ dos2unix <textfile>

And the other way around (Linux-like line breaks to Windows-like line breaks):

[rechosen@localhost linebreaks]$ unix2dos <textfile>

You might wonder why you should ever use this. Well, for example, when opening a file with Linux-like line breaks in Window’s Notepad, the file will appear as one long line and every linebreak will be replaced by two blocks. This is quite annoying. And, the other way around, if you’re trying to run a bash script that contains Windows-like line breaks, bash will fail miserably at interpreting it.
By the way, if you don’t have Linux near to convert a text file with Linux-like line breaks and you need to edit it on Windows, you can also use Wordpad (located at Start => Programs => Accessories => Wordpad) to open the file. Wordpad does support Linux-like line breaks.


Image of Evgeny Chernyavskiy
Evgeny Chernyavskiy
8 years ago

# another option
sed -i 's/r//g' file.ext

Image of John
8 years ago

Good find. Most decent text editors generally has built in commands for converting this as well. Both emacs and vi do, for example. In vim I have the following setting to do a conversion with a short cut key (m). Here is what my vim config file looks like for the same:
noremap m mmHmt:%s///ge’tzt’m

Leave a Reply

Your email address will not be published. Required fields are marked *