Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove ^M characters from file using sed

Tags:

sed

awk

I have this line inside a file:

ULNET-PA,client_sgcib,broker_keplersecurities ,KEPLER 

I try to get rid of that ^M (carriage return) character so I used:

sed 's/^M//g' 

However this does remove everything after ^M:

[root@localhost tmp]# vi test ULNET-PA,client_sgcib,broker_keplersecurities^M,KEPLER  [root@localhost tmp]# sed 's/^M//g' test ULNET-PA,client_sgcib,broker_keplersecurities 

What I want to obtain is:

[root@localhost tmp]# vi test ULNET-PA,client_sgcib,broker_keplersecurities,KEPLER 
like image 216
SoSed Avatar asked Oct 16 '13 14:10

SoSed


People also ask

How do I find Ctrl M characters in Linux?

Note: Remember how to type control M characters in UNIX, just hold the control key and then press v and m to get the control-m character.

How do I get rid of M in vim?

How can I remove ^M characters from text files? A. ^M are nothing more than carriage return, so it is easy to use the search and replace function of vim to remove them. That will do the job.

What is control M character in Unix?

It is known as carriage return. If you're using vim you can enter insert mode and type CTRL - v CTRL - m . That ^M is the keyboard equivalent to \r.


2 Answers

Use tr:

tr -d '^M' < inputfile 

(Note that the ^M character can be input using Ctrl+VCtrl+M)


EDIT: As suggested by Glenn Jackman, if you're using bash, you could also say:

tr -d $'\r' < inputfile 
like image 83
devnull Avatar answered Sep 30 '22 19:09

devnull


still the same line:

sed -i 's/^M//g' file 

when you type the command, for ^M you type Ctrl+VCtrl+M

actually if you have already opened the file in vim, you can just in vim do:

:%s/^M//g 

same, ^M you type Ctrl-V Ctrl-M

like image 25
Kent Avatar answered Sep 30 '22 19:09

Kent