我正在运行以下命令,
set /p "filepath=Drag and drop your file >"
cls
for %%a in ("%filepath%") do echo %%~nxa
pause >nul
当文件名为单个单词时,此方法很好用。但是,当文件名或文件夹名称为多个单词且中间有空格时,此方法无效。
上面运行的代码示例和输出是,
(1)如果输入路径是D:\folder\folder\file.txt
,则输出是,
file.txt
(2)如果输入路径是D:\folder\folder name\file name.txt
,则输出是,
folder
file
name.txt""
但是,(2)的预期输出是,
file name.txt
请帮我修复我的代码。
答案1
@echo off
setlocal enabledelayedexpansion
cls
set /p "filepath=Drag and drop your file >"
set filepath=%filepath:"=%
:repeat
for /f "delims=\ tokens=1*" %%x in ("%filepath%") do (
set filename=%%x
set filepath=%%y
)
if "%filepath%"=="" (
echo %filename%
) else (
goto :repeat
)
endlocal
答案2
简短选项仅保留基于分隔符\
的最后一个字符串set !var:\=!
set "_var_file=c:\this\folder\and\this\subfolder\of\this\file name and extension.log"
@echo off && setlocal enabledelayedexpansion
set /p "filepath=Drag and drop your file >" && set "filepath=!filepath:"=!"
set "_name=%filepath:\=" & set "filepath=%" & cls & call echo/!filepath!
"%__APPDIR__%timeout.exe" /t -1 & endlocal