Linux: how to remove trailing ^M (carriage return)
30th March 2009
Imagine you have some styles.css transferred from Win machine to Linux via FTP in binary mode instead of ASCII mode; then
cat styles.css | tr -d "\r" > styles-nocarriage.css
will create styles-nocarriage.css with ^M’s removed.
Alternative syntax:
tr -d "\r" < styles.css > styles-nocarriage.css
Most editors have global replace features which allow to get rid of control characters using regular expressions (exact instructions are editor-specific).
For multiple files, try this:
for f
do
mv $f ${f}~ && tr -d "\r" <${f}~ >$f
rm ${f}~
done
Save this shell script as a file (e.g. dos2unix.sh), then do ./dos2unix.sh
June 8th, 2009 at 16:34
[...] newlines from the end of all *.php files: find . -type f -name “*.php” -exec /home/user/dos2unix.sh {} [...]
July 8th, 2013 at 2:36
Incase file names/directories contain any spaces, lets add quotes to the multiple files script:
for f
do
mv “$f” “${f}~” && tr -d “\r” “$f”
rm “${f}~”
done
This script will now work great with find and the -exec parameter.
July 8th, 2013 at 10:46
@J – thanks, that is indeed so – I had no spaces in names, thus no quoting.
Do not forget to redirect the output of tr (this part seems missing from your comment): “tr -d \r < ${f}~ >$f”