Convert unix path to windows path

I'm trying to convert a unix style MSYS path such as /c/my/path/to/a/folder to a Windows path, or something that CMake would understand, e.g C:/my/path/to/a/folder. I'd like it to work on a path...

As an alternative to the accepted answer, you may wish to consider that MSYS itself will perform the conversion at any boundary between MSYS parent and native child process; thus, in an MSYS shell console:

cmd //c echo /c/my/path/to/a/folder

would display the appropriately converted path c:/my/path/to/a/folder. Additionally, this technique offers the possible advantage that it will emit the fully converted native form of a path, such as:

cmd //c echo /home/my/path/to/a/folder

to yield its native equivalent C:/MinGW/msys/1.0/home/my/path/to/a/folder, (assuming your MSYS installation is in the recommended default location, at C:/MinGW/msys/1.0).

With the caveat that running MSYS shell without proper initialization, as performed by msys.bat, may not work, (especially when running on 64-bit Windows), you may be able to run an equivalent command from within a native process, (such as within CMake), as:

C:/MinGW/msys/1.0/bin/sh -c 'cmd //c echo /home/my/path/to/a/folder'

Note that, if you invoke this from a native process which is itself running within an MSYS console, the initialization will have been correctly performed for the console’s own shell process, and should thus propagate through the native process; the issues are more likely to arise if you attempt to invoke MSYS processes directly from a cmd.exe process, in a native Windows console, (or other native container).

Also note that, if the path name in question contains spaces, (never a good idea), you may need to enclose it within double quotes:

cmd //c echo "/home/my/path with spaces"

In this case, some experimentation indicates that the double quotes remain within the cmd output. I’m not entirely certain if this is necessary; you should use your discretion in your own particular usage case.

Path Convert

A simple Unix <-> Windows path converter

This is a simple Node tool that will convert back and forth between Windows and Unix-style paths.

The conversion is pretty simple, if the input path contains backslashes () then it assumes Windows -> Unix and if it contains slashes (/) it will convert Unix -> Windows.

Because it’s a Node app it should pretty much work anywhere you have your Node environment set up (Windows CMD, Msys Git command prompt, etc.). It works well in a Windows Msys environment where you’re likely to run into both path styles at some point.

Installation

This tool is designed to be run from the command-line.

npm install --global git://github.com/Coridyn/path-convert.git

This will set up the tool with the global pc command.

Usage

The tool will read the path as an input argument or read it from stdin.

Option 1: Path as an input argument:

$ pc /C/Users/username
C:Usersusername

Option 2: Read from stdin:

$ pc
Enter path:
C:Usersusername
/C/Users/username

You can easily chain it together with other commands too.

On Windows:

In Bash (or similar shells):

On Windows copy the converted path to the clipboard like this:

In a Bash shell on Windows:

NOTE: On Unix-style shells you might need to escape or quote backslashes.

If you get output like this:

pc c:Usersusername
c:Usersusername

Quote the input path:

pc "c:Usersusername"
/c/Users/username

Or escape the backslashes:

pc c:\Users\username
/c/Users/username
  1. Always double-quote your variables so that you don’t need to care about spaces or shell meta-characters.

  2. you can use sed or tr to convert /s to . e.g. sed 's:/:\:g' or tr '/' '\' (note: because is the shell escape character, it needs to be escaped to be treated as a literal backslash).

  3. Alternatively, bash’s string manipulation operators will do the job (but aren’t posix standard, so aren’t portable). The only mistake you made there was in not quoting the variables.

But note that, as mentioned by @Michael Homer, it shouldn’t be necessary to modify the path separator…I’ve certainly had no difficulty running wine program.exe /unix/path/to/file in the past.

resulting in:

#!/bin/bash

p1="$1"
p2="$2"

# optional transformation
p1="$(printf "%s" "$p1" | tr '/' '\')"
p2="$(printf "%s" "$p2" | tr '/' '\')"

wine /utils/wincmp.exe "$p1" "$p2"

or

#!/bin/bash

p1="${1////\}"
p2="${2////\}"

wine /utils/wincmp.exe "$p1" "$p2"

or even:

#!/bin/bash
wine /utils/wincmp.exe "${1////\}" "${2////\}"

(but this last version doesn’t give you any opportunity to sanity-check the file arguments, or do any kind of option handling — e.g. with getopts)


Finally, you may want to reconsider your preference for a Windows diff tool, or at least conduct a more thorough survey before deciding (you’ve only evaluated a small subset of available tools and GUI wrappers). A Windows/wine based tool will not integrate pleasantly into Linux/UNIX-based development workflow.

(personally, I mostly use either diff -u or colordiff -u piped into less. Given that I’m working with text files, there’s no need for a GUI interface. It’s also identical to what I get from git diff etc. On the rare occasions I need a side-by-side diff, I mostly use sdiff).

Tool to convert Unix paths to/from Win32 paths

Synopsis

winepath option {path}

Description

winepath is a tool to convert a Unix path to/from a Win32 (short/long) path compatible with its Microsoft Windows counterpart.

If more than one option is given then the input paths are output in all formats specified, in the order long, short, Unix, Windows. If no option is given the default output is Unix format.

Options

-u, —unix

converts a Windows path to a Unix path.

-w, —windows

converts a Unix path to a long Windows path.

-l, —long

converts the short Windows path of an existing file or directory to the long format.

-s, —short

converts the long Windows path of an existing file or directory to the short format.

-0

separate output with character, instead of a newline.

-h, —help

shows winepath help message and exit.

Bugs

Bugs can be reported on the Wine bug tracker.

Availability

winepath is part of the Wine distribution, which is available through WineHQ, the Wine development headquarters.

See Also

wine(1),
Wine documentation and support.

Info

November 2010 Wine 8.0 Wine Programs

Many of our build processes are made up of a mix of Cygwin tools (makepkg/bash for
starters) and native Windows tools. When building things the paths of input and
output files and directories are often communicated between them via process
arguments or environment variables. The problem here is that those are in many
cases not compatible:

  • C:nope is not a valid Unix path and n might make problems when being
    interpreted as an escape sequence.
  • C:/nope is slightly better, because, while it’s not a valid Unix path, if
    it’s just forwarded to some other Windows tools things might work out fine.
  • /foo is both a valid Windows path (drive relative path evaluating to
    C:foo for example) and a valid Unix path, but resolves to a different path.
    Again, if it’s just forwarded to some other Unix tool then things might work
    out fine.
  • foo/bar.txtjust works, relative to the current working directory, while
    foobar.txt is only OK with native tools.
  • Path lists, commonly used in environment variables like FOO=/foo:/bar also
    will never work, since paths are separated by ; on Windows and not :,
    similarly c:/foo could be interpreted as a Unix path list containing c and
    /foo when a path list is expected.

The only solution here is to avoid mixing Unix/Cygwin and native tools outside
of makepkg (preferred) or convert them when they get passed between the
different programs. For the latter MSYS2 provides an automatic conversion that
just works automatically in many cases.

Manual Unix ⟷ Windows Path Conversion

MSYS2 ships the Cygwin tool cygpath by default which allows converting paths
between the Unix format, Windows format, and mixed format, see cygpath --help
for details.

$ cygpath -u C:\foo
/c/foo
$ cygpath -m /mingw64/bin
C:/msys64/mingw64/bin
$ cygpath -w /mingw64/bin
C:msys64mingw64bin

Automatic Unix ⟶ Windows Path Conversion

Process Arguments

When calling native executables from the context of Cygwin then all the
arguments that look like Unix paths will get auto converted to Windows. For
example when calling native Python from the context of bash:

$ python3 -c "import sys; print(sys.argv)" --dir=/foo
['-c', '--dir=C:/msys64/foo']
$ python3 -c "import sys; print(sys.argv)" --dir=/foo:/bla
['-c', '--dir=C:\msys64\foo;C:\msys64\bla']

While this is helpful in many cases it’s also not perfect and in corner cases
converts arguments that look like Unix paths while they are not, or detects
lists of Unix paths where there are none. For these cases you can exclude
certain arguments via the MSYS2_ARG_CONV_EXCL environment variable:

$ MSYS2_ARG_CONV_EXCL='--dir=' python3 -c "import sys; print(sys.argv)" --dir=/foo
['-c', '--dir=/foo']

MSYS2_ARG_CONV_EXCL can either be * to mean exclude everything, or a list of
one or more arguments prefixes separated by ;, like
MSYS2_ARG_CONV_EXCL=--dir=;--bla=;/test. It matches the prefix against the
whole argument string.

Environment Variables

Similar to process arguments, paths in environment variables get converted too:

$ MYVAR=/foo python3 -c "import os; print(os.environ['MYVAR'])"
C:/msys64/foo
$ MYVAR=/foo:/bar python3 -c "import os; print(os.environ['MYVAR'])"
C:msys64foo;C:msys64bar

You can disable the conversion with MSYS2_ENV_CONV_EXCL:

$ MSYS2_ENV_CONV_EXCL='MYVAR' MYVAR=/foo python3 -c "import os; print(os.environ['MYVAR'])"
/foo

MSYS2_ENV_CONV_EXCL can either be * to mean exclude everything, or a list of
one or more environment variable prefixes separated by ;, like
MSYS2_ENV_CONV_EXCL=FOO;BAR;/test. It matches the prefix against the following
string KEY=VALUE.

Cygwin special cases some environment variables that are known to be paths or
path lists and does less guessing with them. For example HOME will never be
interpreted as a path list even if it contains :.

Windows ⟶ Unix Path Conversion

You might wonder why calling things like ls C:/ might work and suspect that
again auto conversion is used, but that’s not the case:

$ /usr/bin/python3 -c "import sys, os; print(sys.argv, os.listdir(sys.argv[1]))" C:/
['-c', 'C:/'] ['$Recycle.Bin', '$SysReset', ...]

Cygwin which provides the POSIX API will just forward the paths to the Windows
API as is. This works as long as the tool does not try to interpret the path too
much and just forwards it to the system API. If that doesn’t work in your case
you can use cygpath:

$ /usr/bin/python3 -c "import sys, os; print(sys.argv, os.listdir(sys.argv[1]))" "$(cygpath -u C:/)"
['-c', '/c/'] ['$Recycle.Bin', '$SysReset', ...]

The package prefix (hack)

When looking at some of our package recipes you might have seen something like:

MSYS2_ARG_CONV_EXCL="--prefix=" 
  meson 
    --prefix="${MINGW_PREFIX}" 
    ...

which results in meson --prefix=/mingw64 ... being executed.

/mingw64 in this case is the UNIX prefix where the package will be installed
to and in addition is a valid Windows path (a drive relative path, so
C:mingw64), so the native build tools will concatenate it with DESTDIR and
copy things to the right place.

In the native Windows world this path doesn’t make much sense, as C:mingw64
likely doesn’t match where the software lives, but ideally all native Windows
tools are relocatable and won’t use the prefix at runtime anyway. And if they do
and happen to call Cygwin tools then the prefix resolves to the correct path
because the Cygwin root path is relocatable.

winepath is the helper program to convert file paths between UNIX and Windows.

Usage

Usage: winepath [OPTION] [PATH]...
Convert PATH(s) to Unix or Windows long or short paths.

  -u, --unix    converts a Windows path to a Unix path
  -w, --windows converts a Unix path to a long Windows path
  -l, --long    converts the short Windows path of an existing file or
                directory to the long format
  -s, --short   converts the long Windows path of an existing file or
                directory to the short format
  -h, --help    output this help message and exit
  -v, --version output version information and exit

If more than one option is given then the input paths are output in all formats specified, in the order long, short, Unix, Windows.

If no option is given the default is Unix format.

Examples

$ winepath c:\
/home/vitaliy/.wine/dosdevices/c:/

$ winepath "c:program files"
/home/vitaliy/.wine/dosdevices/c:/Program Files

$ winepath -w ~
z:homevitaliy

$ winepath -w /media/dvd/
d:

To launch documents from inside Windows apps, create a small shell script called e.g. /usr/bin/run_prog containing

#!/bin/sh
$1 "`wine winepath -u "$2"`"

And then add a registry entry like this:

[HKEY_CLASSES_ROOTxcelfileShellOpencommand]
@="/bin/sh run_prog /usr/bin/oocalc "%1""

See also winenative — Tres Finocchiaro’s script that uses winepath to launch Linux apps from inside Windows apps

Name

cygpath — Convert Unix and Windows format paths, or output system path information

Synopsis

cygpath { -d | -m | -u | -w | -t TYPE } [-f FILE] [-i] [CONVERSION_OPTION…] NAME

cygpath [-c HANDLE]

cygpath [-A] { -D | -H | -O | -P | -S | -W | -F ID }

cygpath -h | -V

Options

Output type options:

  -d, --dos             print DOS (short) form of NAMEs (C:PROGRA~1)
  -m, --mixed           like --windows, but with regular slashes (C:/WINNT)
  -M, --mode            report on mode of file (currently binmode or textmode)
  -u, --unix            (default) print Unix form of NAMEs (/cygdrive/c/winnt)
  -w, --windows         print Windows form of NAMEs (C:WINNT)
  -t, --type TYPE       print TYPE form: 'dos', 'mixed', 'unix', or 'windows'

Path conversion options:

  -a, --absolute        output absolute path
  -l, --long-name       print Windows long form of NAMEs (with -w, -m only)
  -p, --path            NAME is a PATH list (i.e., '/bin:/usr/bin')
  -U, --proc-cygdrive   Emit /proc/cygdrive path instead of cygdrive prefix
                        when converting Windows path to UNIX path.
  -s, --short-name      print DOS (short) form of NAMEs (with -w, -m only)
  -C, --codepage CP     print DOS, Windows, or mixed pathname in Windows
                        codepage CP.  CP can be a numeric codepage identifier,
                        or one of the reserved words ANSI, OEM, or UTF8.
                        If this option is missing, cygpath defaults to the
                        character set defined by the current locale.

System information:

  -A, --allusers        use `All Users' instead of current user for -D, -P
  -D, --desktop         output `Desktop' directory and exit
  -H, --homeroot        output `Profiles' directory (home root) and exit
  -O, --mydocs          output `My Documents' directory and exit
  -P, --smprograms      output Start Menu `Programs' directory and exit
  -S, --sysdir          output system directory and exit
  -W, --windir          output `Windows' directory and exit
  -F, --folder ID       output special folder with numeric ID and exit

Other options:

  -f, --file FILE       read FILE for input; use - to read from STDIN
  -o, --option          read options from FILE as well (for use with --file)
  -c, --close HANDLE    close HANDLE (for use in captured process)
  -i, --ignore          ignore missing argument
  -h, --help            output usage information and exit
  -V, --version         output version information and exit

Description

The cygpath program is a utility that converts
Windows native filenames to Cygwin POSIX-style pathnames and vice versa.
It can be used when a Cygwin program needs to pass a file name to a
native Windows program, or expects to get a file name from a native
Windows program. Alternatively, cygpath can output
information about the location of important system directories in either
format.

The -u and -w options indicate
whether you want a conversion to UNIX (POSIX) format
(-u) or to Windows format (-w). Use
the -d to get DOS-style (8.3) file and path names. The
-m option will output Windows-style format but with
forward slashes instead of backslashes. This option is especially useful
in shell scripts, which use backslashes as an escape character.

In combination with the -w option, you can use
the -l and -s options to use normal
(long) or DOS-style (short) form. The -d option is
identical to -w and -s together.

The -C option allows to specify a Windows codepage
to print DOS and Windows paths created with one of the
-d, -m, or -w
options. The default is to use the character set of the current locale
defined by one of the internationalization environment variables
LC_ALL, LC_CTYPE, or LANG,
see the section called “Internationalization”. This is sometimes not sufficient for
interaction with native Windows tools, which might expect native,
non-ASCII characters in a specific Windows codepage. Console tools, for
instance, might expect pathnames in the current OEM codepage, while
graphical tools like Windows Explorer might expect pathnames in the
current ANSI codepage.

The -U option allows to use cygpath to create
unambiguous Unix paths pointing outside the Cygwin tree andf thus having
no explicit POSIX path. Those paths usually use the cygdrive prefix.
However, the cygdrive prefix can be changed by the user, so symbolic links
created using the cygdrive prefix are not foolproof. With
-U cygpath will generate such paths prepended by the
virtual /proc/cygdrive symbolic link, which will
never change, so the created path is safe against changing the cygdrive
prefix.

The -C option takes a single parameter:

  • ANSI, to specify the current ANSI
    codepage

  • OEM, to specify the current OEM (console)
    codepage

  • UTF8, to specify UTF-8.

  • A numerical, decimal codepage number, for instance 936 for GBK,
    28593 for ISO-8859-3, etc. A full list of supported codepages is
    listed on the Microsoft MSDN page Code Page Identifiers. A codepage of 0 is the same as if the
    -C hasn’t been specified at all.

The -p option means that you want to convert a
path-style string rather than a single filename. For example, the PATH
environment variable is semicolon-delimited in Windows, but
colon-delimited in UNIX. By giving -p you are
instructing cygpath to convert between these
formats.

The -i option supresses the print out of the usage
message if no filename argument was given. It can be used in make file
rules converting variables that may be omitted to a proper format. Note
that cygpath output may contain spaces (C:Program
Files) so should be enclosed in quotes.

Example 3.5. Example cygpath usage

#!/bin/sh
if [ "${1}" = "" ];
	then
		XPATH=".";
	else
		XPATH="$(cygpath -C ANSI -w "${1}")";
fi
explorer $XPATH &

The capital options -D, -H,
-P, -S, and -W
output directories used by Windows that are not the same on all systems,
for example -S might output C:WINNTsystem32 or
C:WindowsSystem32. The -H shows the Windows profiles
directory that can be used as root of home. The -A
option forces use of the «All Users» directories instead of the current
user for the -D, -O and
-P options. The -F outputs other
special folders specified by their internal numeric code (decimal or
0x-prefixed hex). For valid codes and symbolic names, see the CSIDL_*
definitions in the include file /usr/include/w32api/shlobj.h from package
w32api. The current valid range of codes for folders is 0 (Desktop) to 59
(CDBurn area). By default the output is in UNIX (POSIX) format; use the
-w or -d options to get other
formats.

I wrote a bat file to do this. Just place the file wherever you are working or add it to your path (or just put it above your code, which would be easier to work with). Remember to assign «variable» to your file path first (if you are using a separate file, try using parameters).

What the code does:

1) Get the first letter of the path, which is the drive.

2) Remove the first two letters.

3) Change the slashes.

4) This is the tricky part: since Linux is case sensitive, we need to convert uppercase drive letter to lowercase. Do this by matching each (tell me if there is a better way). You can remove unnecessary drive letters too, since you probably have no more than ten drives.

5) Combine everything to give the final string.

The result:

Input:

E:myfilesapp1datafile.csv

Output (with the quotation marks):

"/mnt/e/myfiles/app1/data/file.csv"

The code is as follows:

@echo OFF

set "variable=E:myfilesapp1datafile.csv"

set "drive=%variable:~0,1%"

set variable=%variable:~2%
set "variable=%variable:=/%"

if %drive%==A set "drive=a"
if %drive%==B set "drive=b"
if %drive%==C set "drive=c"
if %drive%==D set "drive=d"
if %drive%==E set "drive=e"
if %drive%==F set "drive=f"
if %drive%==G set "drive=g"
if %drive%==H set "drive=h"
if %drive%==I set "drive=i"
if %drive%==J set "drive=j"
if %drive%==K set "drive=k"
if %drive%==L set "drive=l"
if %drive%==M set "drive=m"
if %drive%==N set "drive=n"
if %drive%==O set "drive=o"
if %drive%==P set "drive=p"
if %drive%==Q set "drive=q"
if %drive%==R set "drive=r"
if %drive%==S set "drive=s"
if %drive%==T set "drive=t"
if %drive%==U set "drive=u"
if %drive%==V set "drive=v"
if %drive%==W set "drive=w"
if %drive%==X set "drive=x"
if %drive%==Y set "drive=y"
if %drive%==Z set "drive=z"

set "variable=/mnt/%drive%%variable%"

echo "%variable%"

@echo ON

Like this post? Please share to your friends:
  • Convenience rollup update для windows 7 sp1 скачать
  • Convenience rollup update for windows 7 sp1 от microsoft
  • Controller xbox 360 wireless receiver for windows скачать драйвер
  • Controller for windows 10 скачать бесплатно
  • Controlcenter4 brother для windows 10 скачать