Text Processing: Remove Carriage Return

From WikiMLT

Ref­er­ences

Delete a car­riage re­turn (CR) with Sed com­mand

The sub­sti­tute com­mand syn­tax is as fol­lows (to get ^M type CTRL+V fol­lowed by CTRL+M i.e. don’t just type the carat sym­bol and a cap­i­tal 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 syn­tax to re­move car­riage re­turn in Unix or Lin­ux:

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 re­place a car­riage re­turn (CR) with sed com­mand – the syn­tax 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 ver­i­fy ^M in a text file by Cat com­mand

Use the cat com­mand as fol­low:

cat -v input-file

A note about delet­ing or re­plac­ing a line­feed (LF) with sed on Unix or Lin­ux

Use the fol­low­ing syn­tax 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

Re­move a car­riage re­turn with dos2unix com­mand

You can al­so use dos2unix com­mand to con­verts text files from the DOS for­mat to the Unix for­mat:

dos2unix input-file
dos2unix -b input-file

The tr com­mand syn­tax

To delete a CRLF:

tr -d '\r' < input-file > output-file