What is the simplest way to remove all the carriage returns \\r
from a file in Unix?
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.