Remove carriage return in Unix

后端 未结 21 2584
傲寒
傲寒 2020-11-22 03:40

What is the simplest way to remove all the carriage returns \\r from a file in Unix?

21条回答
  •  一向
    一向 (楼主)
    2020-11-22 03:48

    Removing \r on any UNIX® system:

    Most existing solutions in this question are GNU-specific, and wouldn't work on OS X or BSD; the solutions below should work on many more UNIX systems, and in any shell, from tcsh to sh, yet still work even on GNU/Linux, too.

    Tested on OS X, OpenBSD and NetBSD in tcsh, and on Debian GNU/Linux in bash.


    With sed:

    In tcsh on an OS X, the following sed snippet could be used together with printf, as neither sed nor echo handle \r in the special way like the GNU does:

    sed `printf 's/\r$//g'` input > output
    

    With tr:

    Another option is tr:

    tr -d '\r' < input > output
    

    Difference between sed and tr:

    It would appear that tr preserves a lack of a trailing newline from the input file, whereas sed on OS X and NetBSD (but not on OpenBSD or GNU/Linux) inserts a trailing newline at the very end of the file even if the input is missing any trailing \r or \n at the very end of the file.


    Testing:

    Here's some sample testing that could be used to ensure this works on your system, using printf and hexdump -C; alternatively, od -c could also be used if your system is missing hexdump:

    % printf 'a\r\nb\r\nc' | hexdump -C
    00000000  61 0d 0a 62 0d 0a 63                              |a..b..c|
    00000007
    % printf 'a\r\nb\r\nc' | ( sed `printf 's/\r$//g'` /dev/stdin > /dev/stdout ) | hexdump -C
    00000000  61 0a 62 0a 63 0a                                 |a.b.c.|
    00000006
    % printf 'a\r\nb\r\nc' | ( tr -d '\r' < /dev/stdin > /dev/stdout ) | hexdump -C
    00000000  61 0a 62 0a 63                                    |a.b.c|
    00000005
    % 
    

提交回复
热议问题