Search code examples
stringvbscriptoctaveclipboard

Copy String with newline character \n to clipboard via vbscript


In Octave, I have a string

outstr = 'Line1 \n Line2 \n Line3 \n'

which I like to copy to the clipboard and then insert it into an Excel-sheet by pasting from the clipboard.

The clipboard function of octave does not work at all, even for simplest strings. I don't know why. And directly storing to Excel is not an option as not suffiently flexible.

As I am already using vbscript with Octave with other tasks, I'd like to use it in this case as well. So here is what I came up with:

Vbscript (borrowed from the final answer here:

Set objShell1 = WScript.CreateObject("WScript.Shell")
objShell1.Run "cmd /c echo " & Trim(WScript.Arguments(0)) & "|clip"
Set objShell1 = Nothing

which works great for one-line strings.

Then I use this wrapper function in octave:

function copy2clipboard(outstr)

pathWrapper =  fileparts(mfilename('fullpath'));
system( [pathWrapper '\copy2clipboard.vbs "' outstr '"'] );

end

For one-line strings this all works as desired, but VBscript is not able to process the newline character \n. I couldn't manage to substitute it with the VBscript equivalents like VbCrLf.

Solutions working for Matlab are fine, but only using octave-compatible syntax.

What do you suggest?


Solution

  • I finally found a working a solution. The octave wrapper function from the question

    function copy2clipboard(outstr)
       pathWrapper =  fileparts(mfilename('fullpath'));
       system( [pathWrapper '\copy2clipboard.vbs "' outstr '"'] );
    end
    

    can remain unchanged. The VBscript copy2clipboard.vbs has to be adapted as follows to use multiple echo, LFC can be chosen freely:

    Set objShell1 = WScript.CreateObject("WScript.Shell")
    str = Replace(WScript.Arguments(0), "LFC", "&echo ")
    objShell1.Run "cmd /c (echo " & str & "off)|clip"
    Set objShell1 = Nothing
    

    Important to note: The input outstr within Octave/Matlab must not contain the acutal line feed character \n. Instead a pattern of real characters has to be defined. In my case I chose LFC, as it would never appear in my output.