How to add a carriage return before every newline?

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

This is exactly what unix2dos does:

$ unix2dos file.txt

That will replace file.txt in-place with a version with CRLF line endings.

If you want to do it with sed, you can insert a carriage return at the end of every line:

sed -e 's/$/\r/' file.txt

This replaces (s) the zero-size area right before the end of the line ($) with \r. To do in-place replacement (like unix2dos does), use sed -i.bak, although that is a non-standard extension - if you don't have it, use a temporary file.


Doing this with POSIX is tricky:

  • POSIX Sed does not support \r or \15. Even if it did, the in place option -i is not POSIX

  • POSIX Awk does support \r and \15, however the -i inplace option is not POSIX

  • d2u and dos2unix are not POSIX utilities, but ex is

  • POSIX ex does not support \r, \15, \n or \12

To remove carriage returns:

awk 'BEGIN{RS="\1";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

awk 'BEGIN{RS="\1";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file

Tags:

Grep

Sed

Newlines