How to remove carriage return in Linux or Unix

There are several ways to remove carriage returns (also known as “line endings” or “newline characters”) in Linux or Unix. Some common methods include:

  1. Using the “tr” command:
tr -d '\r' < input.txt > output.txt

This command uses the “tr” (translate) command to delete all occurrences of the carriage return character (\r) from the input file and save the output to a new file.

  1. Using the “sed” command:
sed 's/\r//g' input.txt > output.txt

This command uses the “sed” command to find and replace all occurrences of the carriage return character (\r) with nothing, and save the output to a new file.

  1. Using the “awk” command:
awk '{ sub("\r$", ""); print }' input.txt > output.txt

This command uses the “awk” command to remove the carriage return character from the end of each line in the input file and save the output to a new file.

  1. Using the “dos2unix” command
dos2unix input.txt output.txt

This command is useful when you are trying to convert windows end of lines to Unix end of lines.

You can also use above command on a single file and it will change the file in place.

dos2unix input.txt

Please note that these commands will not change the original file, instead it will create a new file with the desired changes.

Leave a Comment