Autarchy of the Private Cave

Tiny bits of bioinformatics, [web-]programming etc

    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 . This script accepts wildcards (e.g. ./dos2unix.sh *.php), so be careful!

    Share

    3 Responses to “Linux: how to remove trailing ^M (carriage return)”

    1. Best method to recursively chmod/process files or directories »Autarchy of the Private Cave Says:

      [...] newlines from the end of all *.php files: find . -type f -name “*.php” -exec /home/user/dos2unix.sh {} [...]

    2. J Says:

      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.

    3. Bogdan Says:

      @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”

    Leave a Reply

    XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>