Removing "^M" from the end of a String (i.e. "Ctrl+M")?

Hello All,

I have an Expect script that ssh's to a remote server and runs some commands before exiting.
One of the commands I run is the "hostname" Command. After I run this command I save the output
using this line in the code below...

Basically it executes the hostname command, then I loop through the "$expect_out(buffer)" variable
line by line. The "$expect_out(buffer)" variable holds the output of the last "send" command, up to
the next "expected" ouput.

....
send -- "hostname\r"
expect {
    -re "^hostname.*\r.*" {
        set found 0
        foreach line [split $expect_out(buffer) "\n"] {
            if {$found == 1} {
                set host_name "$line"
                break
            }
            if {[regexp ".*hostname.*" $line]} {
                set found 1
                continue
            }
        }
        puts -nonewline "host_name = \"$host_name\"\n"
    timeout { exit 1 }
    default { exit 11 }
}

The reason I know that it's showing a "^M" at the end of that variable, is because I redirected the output
to a file on one of my tries, and while viewing the output in vi I was able to see the special characters.

And this is the output from the "puts" command. It shows like this below (notice the quotation mark is begin
moved to the start of that line.)...

"ost_name = "My-VM-Host

As you can see the last quotation mark is replacing the first character on the same line...

Any thoughts how I could get rid of this "^M" from my variable..? It would be VERY much appreciated!

Thanks in Advance,
Matt

Try:

regsub -all "\cM" $host_name "" host_name

Hey Chubler_XL, thanks for the reply.

I gave that a shot and I still am getting the same result...
I also switched out your "pattern" with "\^M" and "\\^M" and still no luck.

I ran my Expect Script with the tee command to check out the real output. And if I open the file created from the tee command
I can see this line for the output for the Hostname.

Hostname = "suse-vm-host1^M"

Now if you view the output in STDOUT it looks like this (F.Y.I. I printed it with escaped parentheses to view the start/ending points of the variable)...

"ostname = "suse-vm-host

But anyway, thanks for the "regsub" command though. I've been looking for a command like that.

Thanks Again,
Matt

---------- Post updated at 09:58 AM ---------- Previous update was at 09:53 AM ----------

UPDATE:

Humm... Looks like the "^M" is actually the same thing as a carriage return --> "\r"...
So I switched out the pattern to match with the "\r" and it seems to be working..!!!

regsub -all "\r" $host_name "" host_name

And the output looks good, both in STDOUT and in the file fro the tee command.

Thanks for the regsub command, exactly what I needed! I appreciate your reply.

Thanks Again,
Matt

1 Like