convert crlf to lf

How to Convert CRLF to LF in Linux

Files created in Windows have different Line endings than those created in Linux. Windows adds a Carriage Return Line Feed (CRLF) while Linux adds Line Feed (LF) line endings. When you use a file created in Windows, in Linux, it can lead to errors, especially if it is an executable file like shell script, or python script. So you need to convert line endings, depending on your platform, to be able to use the file properly.


How to Convert CRLF to LF in Linux

There are several ways to convert line endings in Linux. We will look at some of them. Let us say you want to use file data.txt that was created in Windows, in Linux.


1. Using tr command

You can use the Linux command tr to convert Windows Line endings to Linux ones. Here is its syntax.

$ tr -d '\015' <DOS-file >UNIX-file

For example, here is the command to change CRLF to LF in data.txt file.

tr -d '\015' data.txt > data1.txt

In this case, data1.txt will contain Linux LF endings.


2. Using sed command

sed is a popular string editor in Linux. You can use it effectively to convert CRLF to LF and even vice versa. Here is a simple command to convert DOS to Linux line endings and vice versa.

$ sed 's/^M$//' data.txt     # DOS to Unix
$ sed 's/$/^M/' data.txt    # Unix to DOS

Alternatively, you can also use the following commands to replace carriage return.

$ sed $'s/\r$//' data.txt    # DOS to Unix
$ sed $'s/$/\r/' data.txt    # Unix to DOS


3. Using vim

You can also use vim editor to convert line endings from CRLF to LF, and vice versa. Here are the commands to easily convert line endings in file data.txt.

$ vim data.txt -c "set ff=unix" -c ":wq" # dos to unix
$ vim file.txt -c "set ff=dos" -c ":wq" # unix to dios

In the above commands,

“set ff=unix/dos” is to change fileformat (ff) of the file to Unix/DOS end of line format.

“:wq” is to write the file to disk and quit the editor (allowing to use the command in a loop).

If you are going to do this transformation often, you may want to try specific tools such as dos2unix and unix2dos for this purpose.

In this article, we have seen several ways to convert windows line endings to Linux ones and vice versa. Please note, if you are using version control systems like Git to manage your code across platforms, then they automatically convert line endings from one platform to another depending on where you use it. In such cases, you don’t need to explicitly convert line endings in your file as the version control system will automatically do it for you.

Also read:

How to Store Command in Shell Variable
Tar Directory Exclude File & Folders
How to Change Color Scheme in Vim
Python Script to Check URL Status
How to Create Executable in Python

Leave a Reply

Your email address will not be published. Required fields are marked *