Understanding Linux Commands: dos2unix and unix2dos

Prevent problems when moving Windows files to Linux

Linux is the best-known open-source operating system. Occasionally, you may need to move files between Windows and Linux systems. In Windows andDOS files, a line break is indicated by two characters, the carriage return (CR) and line feed (LF). The end of line indicator in Linux and Unix files is indicated by only one character, the carriage return (CR). This difference can cause troublesome hidden characters when you move files between systems.

How to Avoid Hidden Characters

Avoiding hidden characters is relatively painless when you use these two commands:

  • The dos2unix command converts plain text files in Windows to Linux format.
  • The unix2dos command converts plain text files in Linux to Windows format.

These commands affect the line ending of text files. These commands don't alter binary files (unless you force a conversion) or nonregular files such as FIFOs and directories.

Use dos2unix

It's simple to work with dos2unix. It requires an input file to do what you need, and most of the additional options are situation-specific, so you won't encounter these options in more basic situations. For example, convert a DOS file with a basic command, like:

dos2unix text-file.txt

The DOS file is instantly converted to Unix encoding and is ready to use.

If you prefer to keep the original and make a Unix encoded copy, you can accomplish that with this command:

dos2unix -n text-dos.txt text-unix.txt

You'll have two files. One is the original DOS file, and the other is the new Unix copy.

Linux dos2unix command

Use unix2dos

The same thing works in reverse with unix2dos, which converts Unix encoded text files to DOS. This is perfect when exporting something from a Linux machine to a Windows PC. The command is nearly identical:

unix2dos text-file.txt

As before, you can create a DOS encoded copy from a Unix text file:

unix2dos -n text-unix.txt text-dos.txt

The Unix original is preserved, but you'll also have a copy to send to Windows.

Linux unix2dos command

For more information on what dos2unix can do, check out the manual info below.

Syntax

dos2unix [options] [FILE...] [-n INFILE OUTFILE ...]
unix2dos [options] [FILE...] [-n INFILE OUTFILE ...]

Options

The following options are a partial list of the most frequently used options available for dos2unix and unix2dos:

-h, --help  Display help and exit.

-k, --keepdate Keep the date stamp of the output file the same as the input file.

-l, --newline – Add an additional newline.

-q, --quiet  Quiet mode. Suppress all warnings and messages.

-V, --version  Display version information and exit.

-f, --force – Force conversion of binary files.

-s, --safe – Skip binary files (default).

-F, --follow-symlink – Follow symbolic links and convert the targets.

-S, --skip-symlink – Leave symbolic links and targets unchanged (default).