Thursday, October 24, 2024

AutoHotKey Script - Change Windows Paths to Linux/WSL On Paste

If you use a hybrid Windows/WSL environment (like I do) you probably have run into the situation where you copy a path from a Windows program and want to paste it into a Linux program (like a WSL commandline).

The following script does the job and quotes it in case there's spaces.

To use it:

  • Install AHK
  • Copy the following script to an AHK extension and double click it
  • Copy a Windows path (e.g. from Windows Explorer) and paste into a Linux client (e.g. WSL) with Ctl+Alt+v

; Created by Adam Danischewski Copyrighted 2024
; Any use permissible, no warranty expressed or implied.  
; AHK Script - Convert Windows path to WSL path on Ctrl+Alt+V
^!v::
    ; Get clipboard content
    path := A_Clipboard

    ; Ensure path starts with a drive letter
    if RegExMatch(path, "^[A-Z]:", match) {
        ; Replace drive letter with "/mnt/" prefix
        path := StrReplace(path, match, "/mnt/" Format("{:L}",match), 1)  ; Limit replacements to 1
        path := StrReplace(path, ":", "")
    }

    ; Replace backslashes with forward slashes
    path := StrReplace(path, "\", "/")

    ; Wrap the path in quotes and send it
    SendInput % """" path """"
    return