How to add a carriage return before every newline?

  • 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

  • cuonglm

    cuonglm Correct answer

    6 years ago

    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 use perl:

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

    Note that unix2dox won't insert a `CR` before _every_ LF, only before those LFs that are not already preceded by one (and only one) CR.

    @StéphaneChazelas: Thanks for the point, added it to my answer.

    The key piece of information for me here was using `'\r'` with `sed` does the trick.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM