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.

3 responses to “Solution: Converting Line Breaks In Linux”

  1. Evgeny Chernyavskiy says:

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

  2. John says:

    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

  3. […] Solution: Converting Line Breaks In Linux |   If you enjoyed this article, please consider sharing it! […]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Get actionable training and tech advice

We'll email you our latest articles up to once per week.