开发者

Strip drive letter

开发者 https://www.devze.com 2022-12-15 23:22 出处:网络
By using the command from a folder in D: drive for /f \"delims=\"%%d in (\'cd\') do set pathdrv=%%d echo %pathdrv%

By using the command from a folder in D: drive

for /f "delims="  %%d in ('cd') do set pathdrv=%%d

echo %pathdrv%

I get "d:\some folder".I want to write batch commands to create aut开发者_如何学Corun file in the root of the drive. Please help me to strip the drive letter "d:" so the output is "\some folder" and what extra change do i do to strip "\".


Short answer: Use the substring syntax to strip the first two characters from the %cd% pseudo-variable:

%cd:~2%

To remove the first backslash too:

%cd:~3%

This reliably works even with Unicode paths when the console window is set to raster fonts.


Longer answer, detailing some more options (none of which work well enough):

For arguments to the batch file you can use the special syntax %p1, which gives you the path of the first argument given to a batch file (see this answer).

This doesn't work the same way with environment variables but there are two tricks you can employ:

  1. Use a subroutine:

    call :foo "%cd%"
    ...
    goto :eof
    :foo
    set result=%~p1
    goto :eof
    

    Subroutines can have arguments, just like batch files.

  2. Use for:

    for %%d in ("%cd%") do set mypath=%%~pd
    

However, both variants don't work when

  • The console is set to "Raster fonts" instead of a TrueType font such as Lucida Console or Consolas.
  • The current directory contains Unicode characters
    • That have no representation in the current legacy codepage (for Western cultures, CJK is a good choice that doesn't fit). Remember that in this case you'll only get question marks instead of the characters.

The problem with this is that whil environment variables can hold Unicode just fine you'll get into problems once you try setting up a command line which sets them. Every option detailed above relies on output of some kind before the commands are executed. This has the problem that Unicode isn't preserved but replaced by ?. The only exception is the substring variant at the very start of this answer which retains Unicode characters in the path even with raster fonts.


Drive letter:

%CD:~0,1%

Full drive name (incl. colon):

%CD:~0,2%
0

精彩评论

暂无评论...
验证码 换一张
取 消