Remove carriage return in Unix

后端 未结 21 2562
傲寒
傲寒 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:53

    Using sed

    sed $'s/\r//' infile > outfile
    

    Using sed on Git Bash for Windows

    sed '' infile > outfile
    

    The first version uses ANSI-C quoting and may require escaping \ if the command runs from a script. The second version exploits the fact that sed reads the input file line by line by removing \r and \n characters. When writing lines to the output file, however, it only appends a \n character. A more general and cross-platform solution can be devised by simply modifying IFS

    IFS=$'\r\n' # or IFS+=$'\r' if the lines do not contain whitespace
    printf "%s\n" $(cat infile) > outfile
    IFS=$' \t\n' # not necessary if IFS+=$'\r' is used
    

    Warning: This solution performs filename expansion (*, ?, [...] and more if extglob is set). Use it only if you are sure that the file does not contain special characters or you want the expansion.
    Warning: None of the solutions can handle \ in the input file.

提交回复
热议问题