2009-05-25 78 views
2

我需要知道如何从用户输入的文件中提取目录信息,考虑下面的代码为例:[NT Batch]如何从用户输入的文件中获取目录?


ECHO Drag and drop your .txt file here, after that press Enter: 
SET txtfile= 
SET /P txtfile= 
ECHO. 
CD %txtfile% 

ofcourse没有工作,因为我没有从%提取文件路径txtfile% 这里的示例输出我想:

 
C:\>Drag and drop your .txt file here, after that press Enter: 
C:\somefolder\somesubfolder\somefile.txt 
C:\>Press Enter to continue... 

C:\somefolder\somesubfolder\> 

注意到它有变化它的工作目录

回答

2

您可以提取的完整路径如下:

@echo off 
setlocal 
echo Drag and drop your .txt file here, after that press Enter: 
set txtfile= 
set /p txtfile= 
echo. 
for %%i in (%txtfile%) do set txtdir=%%~dpi 
for %%i in (%txtfile%) do set txtfil=%%~nxi 
cd /d %txtdir% 
dir %txtfil% 
endlocal 

第一个for语句获取驱动器和路径,第二个获取文件名和扩展名。我用cd /d来更改驱动器目录,并使用setlocal/endlocal来保存脚本以外的路径(如果您不在意,可以将其删除)。

可以通过运行“for /?”来找到各种〜修饰符。在命令窗口中。它确实是一个强大的命令,并且这些修饰符不限于“for”,它们也可以用于任何%1类型的参数。

+0

伟大的工作:d感谢 – Dels 2009-05-25 09:34:12

1
ECHO Drag and drop your .txt file here, after that press Enter: 
SET txtfile= 
SET /P txtfile= 
ECHO. 
CD %txtfile%\.. 

我真的不知道为什么,但是这个工程在XP中,也可以在NT工作。

+1

它的工作原理,因为XP脑死亡cd命令进行简单的文本换人去掉 ”。”和“..”条目。如果有谁能够认真对待微软的错误,那么有朝一日会有用吗? – paxdiablo 2009-05-25 09:02:51

+0

在XP中工作谢谢,不知道大约NT – Dels 2009-05-25 09:33:53

0

这个问题的答案是用来采取什么样一个人说,并修改它...

paxdiablo是在正确的道路上,但没有被拷贝/ pasteable。为了他的工作正常(也许它只是为了我运行Windows7),你需要2个文件。

的第一个文件:drag_drop.bat

@echo off 
echo Drag and drop your .txt file here, after that press Enter: 
set txtfile= 
set /p txtfile= 
echo.%txtfile% 
call c:\temp\process_filename.bat %txtfile% 

第二个文件:process_filename.bat

FOR %%i in (%txtfile%) do set txtdir=%~dp1 
cmd /K "cd %txtdir%" 

我不得不使用2档的原因是因为它的触发%〜DP1(从paxdiablo语法是错误的 - 没有冒险我知道你有187k代表,我给你的道具[你有%%〜dpi,在回声中使用%%来禁用特殊字符'%'和dp1是分界符允许您从文件名中去除引号,文件路径 - 与%%〜nxi相同的内容])

无论如何,您需要调用批处理文件传递其他文件名。这是第二个进来的地方。这个去除必要的信息,然后允许你访问该路径,然后在你的cmd提示符下打开该目录。

或者

您可以从同一个文件中做到这一点...

@echo off 
setlocal 
IF '%process%'=='1' goto processFile 
echo Drag and drop your .txt file here, after that press Enter: 
set txtfile= 
set /p txtfile= 
echo.%txtfile% 
set process=1 
call c:\temp\dragdrop.bat %txtfile% 

:processFile 
set txtdir= 
FOR %%1 in (%txtfile%) do set txtdir=%~dp1 
cmd /K "cd %txtdir%" 
endlocal