Remove Control-M From Text

Multiple ways to remove control-m from text in linux.

I will try to cover most of them in this post.


The main reason to convert the file is because windows add control-m at the end of each line, which is problematic in linux because it will be interpreted as a character as the rest of the line and will eventually make some scripts failed.


The easiest method is to transfer your file from windows to unix in ASCII format. If you transfer the file in Binary or you ignore the format in which it is transfer, better verify , cause there is a lot of chance your file inherited control-m characters. When you transfer your file , it will be with an ftp or sftp software , most of them are really obvious and you have a settings for the format of the transfer, simple choose ASCII.


To see if a file contain control-m all you need to do is :

1

cat –v filename

OR

2

vi filename

To transfer a file without control-m :

Just transfer the file in ascii mode.

To remove control-m from text :

Here is some example of how to do it :

1

Using ‘dos2unix’ and ‘unix2dos'

(the easiest method, if dos2unix is installed on your system)

  1. dos2unix filename ---- To remove control-m
  2. Unix2dos filename ---- To put back control-m at the end of the line

2

Using ‘tr’
  1. tr –d ‘r’ < file_to_modify > resulting_file
  2. tr –d ‘^M’ < file_to_modify > resulting_file  
  3. In both cases after you need to move back the resulting file into the original file

---- To do the ^M ,  press    [ctrl]+v   followed by    [ctrl]+m

3

Using ‘vi’ --- Very easy also , if the file is not too big
  1. vi filename           --- Position yourself on the first line
  2. :%s/^M//g           --- Then press enter , and voila !

About the Author

Stephane Morin

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Sign up for more great content!

>