Delete ^M Characters

Here is a tip on how to remove pesky control characters from a plain text file? Control characters, aka “carriage returns” can mess things up if you are trying to install a script on your Linux server.

There is more than one way to skin a cat but here are some ways that I personally remove carriage returns from a text file. In these examples, assume that filename is the actual name of your file. All these commands are to be run directly from the command line on your box.

  • Using tr

    tr -d '^M' < input_filename >output_filename
    

  • Using sed

    sed 's/^M$//g' filename > output_filename
    

  • Using awk

    awk '{ sub("\r$", ""); print }' input_filename > output_filename
    

  • Using perl

    perl -p -i -e 's/\r$//' filename
    

  • Using vi

    vi -c "%s/^M//g" -c "wq" filename
    

Choose your poison…

NOTE: Cutting and pasting the above examples will not work unless you are using the perl or awk examples. Simply putting a carat and a capital letter “M” will not work to get the proper ‘^M’ character. So how do you get the ‘^M’ in the command line? Its easy, just do the following:

  1. Keep CTRL key pressed
  2. Press the letter “v” and “m”

Thats it! Enjoy…

UPDATE 10-10-2005: I just found another way using strings

  • Using strings

    strings input_filename > output_filename
    


About this entry