Open In App

How to Convert DOS line endings to Linux line endings using Vim

Last Updated : 07 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

DOS and Unix/Linux file formats differ slightly such that the ASCII characters used at the line endings are different. 

Unix file format uses an LF character to end a line, LF stands for LineFeed, which means moving the cursor down. Unix-based systems and Mac OS X & later use this format. While the DOS file format uses a CR character before the LF character to end a line (usually referred to as CRLF) – CR stands for Carriage Return, which means moving the cursor back to the left margin. DOS and Windows-based systems use this format.

Reading a file written in DOS file format on Unix-based systems in Vim may display unnecessary characters like ^M (or Ctrl-M).

 

 

 

(Vim may automatically detect the format of a file as “dos” i.e. we will see “fileformat=dos” and hence we may not see ^M characters as the file is being read in “dos” format. To see ^M characters we need to read the file in “unix” file format, for this do “:e ++ff=unix” and we should now see ^M characters.)

Solution 1:

To convert such DOS line endings to Unix line endings in vim, perform the following steps:

Step 1:  Edits the file with “dos” file format.

:e ++ff=dos

 

Step 2: Sets the buffer to be written to the file to use Unix line endings.

:set ff=unix

 

Step 3: Write the buffer to the file.

:w

 

These steps work for any combination of DOS and Unix line endings in a file.

Solution 2:

Alternatively, we can search and replace CR characters from DOS line endings in Vim, following the steps given here 

Step 1: To ensure the file is being read in the correct format.

:e ++ff=unix

Step 2:  Replaces each CR character represented by \r with an empty string.

:%s/\r\+$//ge

 

Step 3: Write the buffer to the file.

:w

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads