tags:

views:

79

answers:

2

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 autorun 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 "\".

+2  A: 

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.

tangens
Hm, sorry. I got a little carried away when expanding on your answer. That the actual answer is now a completely different one is an unfortunate side-effect of my research during writing. Feel free to revert.
Joey
A: 

Drive letter:

%CD:~0,1%

Full drive name (incl. colon):

%CD:~0,2%
Nikola Gedelovski