How do I convert between Unix and DOS text files?
The UNIX and DOS operating systems (which includes
Microsoft Windows) differ in the format in which they store text
files. DOS places both a line feed and a carriage return character at
the end of each line of a text file, but Unix uses only a line feed
character. Some DOS applications need to see carriage return
characters at the ends of lines, and may treat Unix-format files as
giant single lines. Some Unix applications won't recognize the
carriage returns added by DOS, and will display Ctrl-m characters at
the end of each line. This appears on the screen as ^M
.
There are many ways to solve this problem. In this document we provide instructions on how to use FTP, screen capture, unix2dos and dos2unix, tr, awk, Perl, and Emacs, to do the conversion. Before you use these utilities, the files you are converting must first be on a Unix computer.
ascii
cat unixfile.txtReplace
unixfile.txt
with the name of the Unix text file
you are transferring. Most communications programs will add carriage
returns to the stream of text as they save it to your PC's hard drive.
Once the file has finished displaying, abort the text download.
dos2unix dosfile.txt unixfile.txtTo convert a Unix file to DOS, enter:
unix2dos unixfile.txt dosfile.txtNote that these utilities are only available on SunOS systems (CDF runs SunOS).
tr -d '\15\32' < dosfile.txt > unixfile.txttr cannot be used to convert a document from Unix format to DOS.
awk '{ sub("\r$", ""); print }' dosfile.txt > unixfile.txtTo convert a Unix file to DOS using awk, at the command line, enter
awk 'sub("$", "\r")' unixfile.txt > dosfile.txtOn some systems, the version of awk may be old and not include the function sub. If so, try the same command, but with
gawk
or
nawk
replacing awk
.
perl -p -e 's/\r$//' < dosfile.txt > unixfile.txtTo convert from a Unix text file to a DOS text file with Perl, at the Unix shell prompt, enter:
perl -p -e 's/$/\r/' < unixfile.txt > dosfile.txtPlease note that you must use single quotation marks in either command line. This prevents your shell from trying to evaluate anything inside.
dosfile.txt
to a Unix text
file using Emacs, a Unix text editor. Enter at the Unix shell prompt:
emacs dosfile.txtThis will open the file in the Emacs text editor. To remove all the "^M" characters, type
M-% C-q C-m RET RET !
Ctrl-z
at the end of
the document. To quickly get to the end of the document in Emacs,
type
M->If you see a
Ctrl-z
at the end of the document, delete it.
unixfile.txt
to a DOS text
file, first open it in Emacs. At the Unix shell prompt, enter
emacs unixfile.txtThis will open the file in the Emacs text editor. To add carriage returns, which will show up as
^M
in Emacs, type
M-% C-q C-j RET C-q C-m C-q C-j RET !It may also be necessary to add a
Ctrl-z
at the end of
the document. At the very end of the document, press
C-q C-z