Sed – How to Add a Carriage Return Before Every Newline

grepnewlinessed

I have a file that only uses \n for new lines, but I need it to have \r\n for each new line. How can I do this?

For example, I solved it in Vim using :%s/\n/\r\n/g, but I would like to use a script or command-line application. Any suggestions?

I tried looking this up with sed or grep, but I got immediately confused by the escape sequence workarounds (I am a bit green with these commands).

If interested, the application is related to my question/answer here

Best Answer

You can use unix2dos (which found on Debian):

unix2dos file

Note that this implementation won't insert a CR before every LF, only before those LFs that are not already preceded by one (and only one) CR and will skip binary files (those that contain byte values in the 0x0 -> 0x1f range other than LF, FF, TAB or CR).

or use sed:

CR=$(printf '\r')
sed "s/\$/$CR/" file

or use awk:

awk '{printf "%s\r\n", $0}' file

or:

awk -v ORS='\r\n' 1 file

or use perl:

perl -pe 's|\n|\r\n|' file
Related Question