HowTo: Convert Between Unix and Windows text files

by on April 18, 2011 · 2 comments· LAST UPDATED April 18, 2011

in

How can I convert newline [ line break or end-of-line (EOL) character ] between Unix and Windows text files?

A newline act as a end of line for all text files. It is a special character and the format of this character differs slightly under Windows and UNIX operating systems. The actual code for displaying a newline vary across oses as follows:

  1. Almost all Unix commands and text editor may display the EOL with Ctrl-m ( ^M ) characters at the end of each line for all text files created on MS-Windows operating systems.
  2. MS-Windows may not display line feed or EOL for all text files created on UNIX operating systems.

Option #1: dos2unix and unix2dos Commands

You can use the dos2unix and unix2dos as follows. To convert newline for a UNIX file to MS-Windows, type:
$ cat -v input.txt
$ unix2dos input.txt output.txt
$ cat -v output.txt
$ vi output.txt

To convert newline for a MS-Windows file to a Unix file, type:
$ cat -v input.txt
$ dos2unix input.txt output.txt
$ cat -v output.txt

Option #2: awk command

You can use the awk command to convert a MS-Windows file to Unix format, type:
$ cat -v input.txt
$ awk '{ sub("\r$", ""); print }' input.txt > output.txt
$ cat -v output.txt

You can convert newline for a Unix file to MS-Windows format, enter:
$ cat -v input.txt
$ awk 'sub("$", "\r")' input.txt > output.txt
$ cat -v output.txt

Please note that the cat command with the -v option is used to display all non-printing characters such as ^ and M- notation, except for LFD and TAB.

See also:

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 2 comments… read them below or add one }

1 Maris December 4, 2013 at 8:15 am

This saved me a lot of effort.

 awk 'sub("$", "\r")' input.txt > output.txt

it replaces line endigs in Linux, so that Windows Notepat can understand, where starts new line. Befor that command Notepad shows everything in one long line, however in Linux there were multiple lines.
Thanks.

Reply

2 bjorn.aigen April 27, 2014 at 3:20 pm

I’m using Ubuntu 12.04. For unix2dos and dos2unix version 5.3.1 (2011-08-09), you must use either of these two syntax (new file mode):

# unix2dos -n infile outfile
# unix2dos –newfile infile outfile

If you use the syntax below then both a.txt and b.txt will be converted to DOS text files.  Both original files will be overwritten and you WILL LOSE the original files:

# unix2dos a.txt b.txt

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , , ,

Previous Faq:

Next Faq: