How can I programmatically (i.e., not using vi
) convert DOS/Windows newlines to Unix?
The dos2unix
and unix2dos
commands are not available on certain systems. How can I emulate these with commands like sed
, awk
, and tr
?
The simplest way to convert line breaks in a text file is to use the dos2unix tool. The command converts the file without saving it in the original format. If you want to save the original file, add the -b attribute before the file name.
To convert from Windows to Linux line breaks you can use the tr command and simply remove the \r characters from the file. The -d option tells the tr command to delete a character, and '\r' specifies the character to delete. The input to tr is redirected from the file fileWindows.
You can use tr
to convert from DOS to Unix; however, you can only do this safely if CR appears in your file only as the first byte of a CRLF byte pair. This is usually the case. You then use:
tr -d '\015' <DOS-file >UNIX-file
Note that the name DOS-file
is different from the name UNIX-file
; if you try to use the same name twice, you will end up with no data in the file.
You can't do it the other way round (with standard 'tr').
If you know how to enter carriage return into a script (control-V, control-M to enter control-M), then:
sed 's/^M$//' # DOS to Unix sed 's/$/^M/' # Unix to DOS
where the '^M' is the control-M character. You can also use the bash
ANSI-C Quoting mechanism to specify the carriage return:
sed $'s/\r$//' # DOS to Unix sed $'s/$/\r/' # Unix to DOS
However, if you're going to have to do this very often (more than once, roughly speaking), it is far more sensible to install the conversion programs (e.g. dos2unix
and unix2dos
, or perhaps dtou
and utod
) and use them.
If you need to process entire directories and subdirectories, you can use zip
:
zip -r -ll zipfile.zip somedir/ unzip zipfile.zip
This will create a zip archive with line endings changed from CRLF to CR. unzip
will then put the converted files back in place (and ask you file by file - you can answer: Yes-to-all). Credits to @vmsnomad for pointing this out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With