dos2unix - Linux


Overview

dos2unix is a command-line utility used to convert text files with DOS or Mac line endings (CR/LF or CR) into Unix/Linux format (LF), making them compatible with various Unix-based systems. This command is particularly useful when transferring text files from Windows (or old Mac systems) to Unix/Linux systems, ensuring that the files maintain their intended formatting and functionality without line-ending issues.

Syntax

The basic syntax for dos2unix is:

dos2unix [options] [file ...] [-n infile outfile ...]
  • file: Specify the file or files to be converted. If no files are mentioned, dos2unix will read from standard input.

Conversion Modes:

  • In-place conversion:
    dos2unix file1.txt
  • Specifying input and output files:
    dos2unix -n input.txt output.txt

Options/Flags

  • -o, –oldfile: Write conversion result back to the input file (in-place conversion).
  • -n, –newfile infile outfile: Convert infile to outfile. Unlike -o, this does not modify the input file.
  • -b, –keep-bom: Keep a Byte Order Mark if it is present. Useful for UTF-8 encoded files.
  • -r, –remove-bom: Remove any Byte Order Mark.
  • -k, –keepdate: Keep the original file date. By default, the file date is updated.
  • -f, –force: Force conversion of binary files.
  • -s, –safe: Skip binary files (safety for preventing corruption).
  • -c, –convmode convmode: Set conversion mode (ascii, 7bit, iso, mac).
  • -d, –info: Display file information instead of converting.

Examples

  1. Basic Conversion:
    Convert a single file in-place from DOS to Unix format.

    dos2unix file1.txt
    
  2. Multiple Files Conversion:
    Convert multiple files simultaneously.

    dos2unix file1.txt file2.txt file3.txt
    
  3. Using New File Mode:
    Create a new file with Unix line endings from a DOS-formatted file.

    dos2unix -n dosfile.txt unixfile.txt
    
  4. Keeping the Original File Date:

    dos2unix -k file1.txt
    

Common Issues

  • Binary File Corruption:
    Be cautious with dos2unix on binary files. Use -s option to skip binary files or -f to force conversion if absolutely necessary.

  • Permission Errors:
    Ensure you have proper permissions on files you’re attempting to convert.

  • No Visible Changes:
    Sometimes, no changes are visible after running the command. Ensure you are viewing the file in a Unix-compatible editor.

Integration

dos2unix can be combined with other Unix tools for powerful scripting and batch processing:

find /path/to/files -type f -name "*.txt" -exec dos2unix {} \;

This command would find and convert all .txt files under /path/to/files to have Unix line endings.

  • unix2dos: Converts Unix text files to DOS format, useful for reverting changes or sharing files with Windows-based systems.

For further information and the latest updates, you can visit the dos2unix official documentation.