DEV Community

Discussion on: Better Copy and Paste in WSL with Two One-Liner Aliases

Collapse
 
emmiep profile image
Emmie Päivärinta

Hi again and thanks for reading my first post to dev.to!

While I was working on this article, I found some slight problems with the aliases regarding how Windows and PowerShell deal with newlines. Most of the time, it probably doesn't even matter, but in some instances it may has a big impact, so I didn't want to leave it out. If you're doing something where it's important the pasted string exactly matches the copied data, like when computing a hash, there are some issues you need to be aware of.

First of all, Windows uses a different character sequence for newlines than Linux and other Unix systems. In Windows, a newline is represented by the "carriage return" character followed by "line feed", which is often represented as CRLF, or \r\n in many programming languages, such as Bash shell scripting. Linux on the other hand just uses the "line feed" character, otherwise LF or \n.

When using Get-Clipboard, newlines always seem to be converted to Windows-style newlines, which might be a problem in some cases. One idea is to use the -Join operator in PowerShell to change the characters used when joining the lines together. This would look something like this:

powershell.exe -Command '(Get-Clipboard) -Join "`n"'
Enter fullscreen mode Exit fullscreen mode

Secondly, by default PowerShell always seems to add a newline to the end of the output. The best solution I've come up with is to pipe the output of Get-Clipboard to Write-Host together with the -NoNewLine flag:

powershell.exe -Command "Get-Clipboard | Write-Host -NoNewLine"
Enter fullscreen mode Exit fullscreen mode

However, I'm not sure if this always works exactly as expected, it might strip the ending newline even when the copied string ends with a newline.

You can combine these commands together, but apparently, there is a way to do both with just Write-Host:

powershell.exe -Command 'Write-Host -NoNewLine -Separator "`n" (Get-Clipboard)'
Enter fullscreen mode Exit fullscreen mode

There may still be some issues, for instance when working with binary data, where both the CRLF and LF character sequences could coexist in the same string and have to be preserved. I'm not entirely sure if it's possible to work around this problem, maybe by invoking C# functions for copy and paste instead.

I'd be grateful if somebody with better PowerShell skills than mine (which are pretty lacking) could provide some feedback. And if anybody is interested in an elaboration on the issues, I could do that too. Once I understand the problem better I would like to update the article or write a follow-up.