1828584 Members
2683 Online
109982 Solutions
New Discussion

Removing ^M from string

 
SOLVED
Go to solution
Henry Chua
Super Advisor

Removing ^M from string

Hi all,

I try this to remove "^M" from a string.. but does not seem to work.. anyone know why??
.....
my $var = "testing123^M";
$var = s/^V^M//;
print "var=$var";
....

Thanks
Henry
6 REPLIES 6
Patrick Wallek
Honored Contributor

Re: Removing ^M from string

If you have a whole file, use the dos2ux command.

# dos2ux file1 > file2

will remove all ^M sequences from file1 and save it in file2.

Henry Chua
Super Advisor

Re: Removing ^M from string

Hi Patrick,

I'll like to implement this to control the string parse to a text so i am using perl to do this. Thanks.

Best regards
Henry
Hein van den Heuvel
Honored Contributor
Solution

Re: Removing ^M from string



Henry,

The ^M or 'CR = Carriage Return" is best represented in perl as \r
You could also use the octal code \012.

Compare this with the more common ^J or 'LF = LineFeed'
For that one you know to use \n or \015.

See: http://www.perl.com/doc/manual/html/pod/perlop.html

Look for 'interpolation'

And also check an ascii table. For example:
http://www.asciitable.com/


Hein.
Peter Nikitka
Honored Contributor

Re: Removing ^M from string

Hi,

if you run perl under windows, you may have to use 'binmode' before you use 'print'.

In your example, the syntax must be adjusted; I suggest:

...
($var1 = $var) =~ s/\r//;
print $var1;
...

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
H.Merijn Brand (procura
Honored Contributor

Re: Removing ^M from string

As Hein said. CR is \r, not ^M
If you want to denote it in CTRL terms, perl offers you \cM, but that is unportable (think EBCDIC), as you now tell exactly which codepoint you use instead of using the correct escape

^V^M is a vi or shell notation. Ctrl-V tells both to take the next character literally. Perl doesn't know about that.

As \r (or \cM) is whitespace, it also falls in that category, and

(my $var = "testing123 \r") =~ s/\s+$//;

will now remove both the \r and the space

Note also that you 'print "var = $var";' will not print a newline unless you used the -l option on perl invocation. That should probably be 'print "var = $var\n";'

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
PAVIC Thierry
Frequent Advisor

Re: Removing ^M from string

try those 2 ways

cat | tr -d "^V^M" >

sed -e "s/^V^M//" >