Text Processing: Remove Carriage Return
From WikiMLT
References
- Main source of the article: Remove ^M Carriage Return (Line Feed / CRLF) on Linux or Unix on nixCraft
- Reference: bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory
- Reference: How do I convert between Unix and Windows text files?
Delete a carriage return (CR) with Sed command
The substitute command syntax is as follows (to get ^M
type CTRL+V followed by CTRL+M i.e. don’t just type the carat symbol and a capital M
. It will not work):
sed -e 's/^M//g' input-file
sed -e 's/^M//g' input-file > output-file
# GNU/sed syntax
sed -i 's/^M//g' input
# Replace it with FOO
sed -i -e 's/^M/FOO/g' input
Or easy to use sed
syntax to remove carriage return in Unix or Linux:
sed 's/\r$//' input-file > output-file
sed 's/\r$//g' input-file > output-file
# GNU/sed syntax
sed -i 's/\r$//g' input
To replace a carriage return (CR) with sed
command – the syntax is:
sed 's/\r/YOUR-replacement-TEXT-HERE/' input-file > output-file
sed 's/\r/YOUR-replacement-TEXT-HERE/g' input-file > output-file
sed 's/\r/foo/g' input-file > output-file
How to verify ^M in a text file by Cat command
Use the cat command as follow:
cat -v input-file
A note about deleting or replacing a linefeed (LF) with sed on Unix or Linux
Use the following syntax if you do not want to delete \n
(new line):
sed ':a;N;$!ba;s/\n//g' input-file -i.bak
sed ':a;N;$!ba;s/\n//g' input-file > output-file
Remove a carriage return with dos2unix command
You can also use dos2unix
command to converts text files from the DOS format to the Unix format:
dos2unix input-file
dos2unix -b input-file
The tr command syntax
To delete a CRLF:
tr -d '\r' < input-file > output-file