Windows PATH to posix path conversion in bash

前端 未结 6 1541
北荒
北荒 2020-12-04 16:35

How can I convert a Windows dir path (say c:/libs/Qt-static) to the correct POSIX dir path (/c/libs/Qt-static) by

6条回答
  •  一向
    一向 (楼主)
    2020-12-04 17:27

    Here is my implementation (tested on git bash).

    From POSIX to Windows

    sed '
        \,/$, !s,$,/,
        \,^/, s,/,:/,2
        s,^/,,
        s,/,\\,g
        ' <<< "$@"
    

    Works for:

    /c/git
    relative/dir
    c:/git
    ~
    .
    ..
    /c
    /c/
    ./relative/dir
    /sd0/some/dir/
    

    except

    /
    
    

    Explanation:

    \,^/, s,/,:/,2 (converts /drive/dir/ to /drive:/dir/) is the heart of it and inserts : before the 2nd /. I use , for delim instead of / for readability. If starting with / (\,^/,), then replace / with :/ for the 2nd occurrence. I do not want to assume drive letter length of 1 so this works for /sd0/some/dir.

    s,^/,, removes the leading / and s,/,\\,g converts all / to \.

    \,/$, !s,$,/, is to handle the corner case of /c and ensure 2nd / (/c/) for the next command to work.

    Note:

    If here string <<< does not work in your shell then you can echo and pipe as

    echo "$@" | sed ...
    

    Errata

    Here e script

提交回复
热议问题