0

I wanted to remove the last forward slash of a directory string so that I use the same path for forfiles tool to delete old files. I have tried the solution here but it didn't work. The script saves the output to a text file so that I see the result. The forfiles doesn't work as the directory is incorrect format. What I want to just to remove the last backward slash "C:\Database\Backup\".

The runable code below is what I have attempted. The problem is line 6, which outputs "C:\Database\Backup\" :~0,-1 instead of "C:\Database\Backup"

set BACKUP_DIR="C:/Database/Backup/"
set LOG_FILE=%BACKUP_DIR%log_file.txt
if not exist BACKUP_DIR mkdir %BACKUP_DIR% 
set BACKWARD_SLASH_DIR=%BACKUP_DIR:/=\% 
echo %BACKWARD_SLASH_DIR% > %LOG_FILE% 
set DELETE_DIR=%BACKWARD_SLASH_DIR%:~0,-1%
echo %DELETE_DIR% >> %LOG_FILE% 
forfiles -p %DELETE_DIR% -s -m *.* -d -1 -c "cmd /c echo Deleted @file" >> %LOG_FILE% 
forfiles -p %DELETE_DIR% -s -m *.* -d -1 -c "cmd /c del @path" 
Community
  • 1
  • 1
wondim
  • 697
  • 15
  • 29
  • 4
    `DELETE_DIR=%BACKWARD_SLASH_DIR%:~0,-1%` -too many % symbols, remove the one after _DIR – TessellatingHeckler Apr 15 '16 at 16:56
  • When I do that, the output is `"C:\Database\Backup\"` – wondim Apr 15 '16 at 17:20
  • Are you sure the output isn't `"C:\Database\Backup\ ` and it's cut off the trailing quote `"` ? That's what I expect now. Try `~0,-2%` ... – TessellatingHeckler Apr 15 '16 at 17:24
  • Yes, I am very sure. with `~0,-2%` it still returns with the slash. – wondim Apr 15 '16 at 17:32
  • 1
    This is a good example of why you should always `set "variable=value"` with the `"variable=value"` pair quoted. That way, the quotation marks aren't part of the variable value, and you can explicitly quote `"%variable%"` when necessary. It also removes ambiguity and ensures that there's no trailing whitespace inadvertently added to the end of the value. Matter of fact, in the code you pasted, there is an extra space at the end of your `set BACKWARD_SLASH_DIR=%BACKUP_DIR:/=\% ` line. – rojo Apr 15 '16 at 19:32
  • Thank you very much! It works now! Quoting the variable and value did the trick. Could you answer it. – wondim Apr 15 '16 at 21:02

1 Answers1

1

This is a good example of why you should always set "variable=value" with the "variable=value" pair quoted. That way, the quotation marks aren't part of the variable value, and you can explicitly quote "%variable%" when necessary. It also removes ambiguity and ensures that there's no trailing whitespace inadvertently added to the end of the value. Matter of fact, in the code you pasted, there is an extra space at the end of your set BACKWARD_SLASH_DIR=%BACKUP_DIR:/=\% line.

rojo
  • 24,000
  • 5
  • 55
  • 101