Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script

How can I programmatically (i.e., not using vi) convert DOS/Windows newlines to Unix?

The dos2unix and unix2dos commands are not prepared on some systems. How can I emulate these with commands like sed, awk, and tr?
by

3 Answers

espadacoder11
Use:

tr -d "\r" < file

Take a look here for examples using sed:

# In a Unix environment: convert DOS newlines (CR/LF) to Unix format.
sed 's/.$//' # Assumes that all lines end with CR/LF
sed 's/^M$//' # In Bash/tcsh, press Ctrl-V then Ctrl-M
sed 's/\x0D$//' # Works on ssed, gsed 3.02.80 or higher

# In a Unix environment: convert Unix newlines (LF) to DOS format.
sed "s/$/`echo -e \\\r`/" # Command line under ksh
sed 's/$'"/`echo \\\r`/" # Command line under bash
sed "s/$/`echo \\\r`/" # Command line under zsh
sed 's/$/\r/' # gsed 3.02.80 or higher

Use sed -i for in-place conversion, e.g., sed -i 's/..../' file.
pankajshivnani123
You can use Vim programmatically with the option -c {command}:

DOS to Unix:
vim file.txt -c "set ff=unix" -c ":wq"

Unix to DOS:
vim file.txt -c "set ff=dos" -c ":wq"

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

":wq" means write the file to disk and quit the editor (allowing to use the command in a loop).
kshitijrana14
Using AWK you can do:
awk '{ sub("\r$", ""); print }' dos.txt > unix.txt


Using Perl you can do:
perl -pe 's/\r$//' < dos.txt > unix.txt

Login / Signup to Answer the Question.