0

In a batch file, the following returns the drive letter and a colon.

set current_Drive=%~d0
echo %current_Drive%

I need to strip the colon from %current_Drive% so that the variable drive letter itself ( "C" instead of "C:\" ) can be used to create a text file within the batch, such as-

dir/s > "Myfiles on Drive %current_Drive% .txt"

The colon (:) contained in the var %current_Drive% is not a legal character in filenames and needs to be stripped out.

I have tried modifying examples from: What does %~d0 mean in a Windows batch file?

Gerhard
  • 22,678
  • 7
  • 27
  • 43
Hairy Query
  • 35
  • 1
  • 7
  • 2
    `echo %current_Drive:~0,1%` – Stephan Jan 28 '19 at 09:19
  • There is documentation in `help set` and `help for`. – Micha Wiedenmann Jan 28 '19 at 09:25
  • Very helpful, thanks, Solved another problem also. The syntax also functions to echo (LEFT,MID,RIGHT) string characters stored in a windows batch file local variable TYPE-- Example -- set _StringVar=%"abcdefg" echo %tempvar:~4,2% – Hairy Query Jan 28 '19 at 11:14
  • @Stephan please make an answer using your comment. Let's minimize unanswered questions count! – JosefZ Jan 28 '19 at 11:59
  • @JosefZ my opinion is that, as there are lots of substring-questions for batch file on SO, mark it as duplicate (and then delete it [poor duplicate]) instead of keeping it. – double-beep Jan 28 '19 at 12:56

1 Answers1

3

The set command has a few useful features for string manipulation, like substring extraction or substring replacement.

To get only the first character of a variable, use

echo %current_Drive:~0,1%

In :~0,1, ~ means "I want a substring", 0 means "skip 0 characters" and 1 means "take 1 character from here"

Note: this only works for environment variables %var%. It doesn't work with specials like %0 or for variables %%a - you need to assign them to a "normal" variable first.

You could also remove the unwanted part :\ with echo %current_Drive::\=% (replace :\ with nothing), but I'd prefer the first method.

Another way (completely overkill for this task; just for completeness):
Split the string by the colon with a for /f loop:

for /f "tokens=1 delims=:" %%a in ("%current_Drive%") do echo %%a

Advantage: you don't have to know the length of the substring, it takes everything from the start of the string to the delimeter.

Stephan
  • 53,940
  • 10
  • 58
  • 91