Have you ever sent a text file created on a Linux system to someone and have them complain that it looked wrong on macOS or Windows? That may be because these systems handle line endings differently. Fortunately, this is easy to fix with a couple of utilities: Dos2Unix and Unix2Dos.

What’s the Deal With Line Endings?

One difference between Windows and Linux that might make exchanging files difficult is the way they count line endings. This dates back to the days when computers used teletype machines for input and output, which were effectively automatic typewriters.

A newline, also called a linefeed, advances the paper one line, and carriage return moves to the beginning of the line. Command-line interfaces carried on this convention of interpreting newlines.

Windows inherited the MS-DOS convention of counting a newline and a carriage return as one line, while Linux, in turn, carried the Unix tradition of just counting newlines as, well, new lines.

Most of the time, text editors are smart enough to be able to detect files created on different systems and adjust the display accordingly, but you may still run into problems occasionally. You might try to run a script and the interpreter might throw an error because it's expecting lines to end differently.

Using Dos2Unix and Unix2Dos

Dos2Unix manpage

Fortunately, there are a couple of utilities that let you convert line endings in files between formats. They're called Dos2Unix and Unix2Dos.

Although these utilities are common on many Linux installations, if they aren't installed on your system, you can download them using the default package manager.

To convert a file created on a Windows system to Linux, use dos2unix:

        dos2unix file
    

...where file is the name of the file that you want to convert. This program will convert the file from DOS newlines to Unix ones in place, as the name suggests. If you want to convert a copy of the file, use the -n option:

        dos2unix -n file1 file2
    

...where file1 and file2 are the names of the original file and the output file. The unix2dos command works the same way and takes the same arguments.

An alternate option is to use a text editor on either Linux or Windows to convert files, as they can also detect and change line ending behavior.

Related: Unix vs. Linux: The Differences Between and Why It Matters

Now Your Text Files Look Right on Any System

With this pair of utilities, you can make sure any text file will work on either Windows or Linux. Fixing newlines is now easier than ever with dos2unix and unix2dos.

In the real world, Linux users and Windows users often need to share files. Fortunately, it's very easy to do so these days.