Dos2unix


Ever wondered what ^M is doing at the end of each line in your code when running git diff? This has most likely something to do with that the file has been edited in a Windows system.

public class Hello {^M
    public static void main(String[] args) {^M
      System.out.println("Hello World!");^M
    }^M
}^M

Windows, or actually DOS is using CRLF (Carriage return + Line feed) as their line endings while Unix only uses LF (Line feed) their line endings.

Why bother about the ^M? My code works anyway.

Yes, most likely it does. Though this often cause text files that have been transferred between systems of different types to be displayed incorrectly. For example, files first created in a Unix system may appear as just a single line of text in Windows system. When creating a new file on a Windows system and then reading them on a Unix system the extra CR may be displayed as M or at the end of each line or as a second line break.

Solution

Use the dos2unix command.

This will convert the a.txt to use LF instead of CRLF.

$ dos2unix a.txt

This will run dos2unix all files in the current directory.

$ find . -type f -exec dos2unix {} \;

For more information about dos2unix options, please see the dos2unix man page.

$ man dos2unix