Replace \n with \r\n in Unix file Replace \n with \r\n in Unix file unix unix

Replace \n with \r\n in Unix file


When faced with this, I use a simple perl one-liner:

perl -pi -e 's/\n/\r\n/' filename

because sed behavior varies, and I know this works.


  • What is the problem with getting dos2unix onto the machine?
  • What is the platform you are working with?
  • Do you have GNU sed or regular non-GNU sed?

On Solaris, /usr/bin/sed requires:

sed 's/$/^M/'

where I entered the '^M' by typing controlV controlM. The '$' matches at the end of the line, and replaces the end of line with the control-M. You can script that, too.

Mechanisms expecting sed to expand '\r' or '\\r' to control-M are going to be platform-specific, at best.


You don't need the -e option.

$ matches the endline character. This sed command will insert a \r character before the end of line:

sed 's/$/\r/' myfile