Windows 命令行字符串解析:字符串中的文件夹和文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6595977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows command line string parsing: folder and filename in string
提问by Vlad
Is there a quick way to get the filename and last folder from a full file path (string) in Windows command line?
有没有一种快速的方法可以从 Windows 命令行中的完整文件路径(字符串)中获取文件名和最后一个文件夹?
I would expect for input -> results:
我希望输入 -> 结果:
"c:\test\test.txt" -> "2", "test.txt"
"c:\test\a.txt" -> "3", "a.txt"
"c:\testfor %I in (c:\test\a.txt) do set path=%~pI
for %I in (c:\test\a.txt) do set file=%~nxI
set pth2=%path:~0,-1%
for %I in (%pth2%) do set lastdir=%~nxI
echo %file% %lastdir%
\b.txt" -> "0", "b.txt"
"c:\c.txt" -> "", "c.txt"
I've been banging my head at this using FOR /F but since the full path can be any length, I can't figure it out.
我一直在使用 FOR /F 对此感到头疼,但由于完整路径可以是任意长度,我无法弄清楚。
回答by deStrangis
Try this:
尝试这个:
echo off
set apath=c:\test\a.txt
call :reverse "%apath%"
for /f "tokens=1,2 delims=\" %%a in ("%reverse.result%") do set afile=%%a&set adir=%%b
call :reverse "%apath%"
set apath = %reverse.result%
call :reverse "%afile%"
set afile= %reverse.result%
rem handle no dir;
if "%adir:~0,1%"==":" set adir=
echo File: %afile%
echo Dir: %adir%
goto:eof
:reverse
set reverse.tmp=%~1
set reverse.result=
:reverse.loop
set reverse.result=%reverse.tmp:~0,1%%reverse.Result%
set reverse.tmp=%reverse.tmp:~1,999%
if not "%reverse.tmp%"=="" goto:reverse.loop
goto:eof
eof:
The Windows Command Line Referenceis your friend.
在Windows命令行参考是你的朋友。
回答by Alex K.
FOR/TOKENS would work if the path were reversed so what about;
如果路径颠倒了,FOR/TOKENS 会起作用,那么怎么样?
File: a.txt
Dir: 3
For
为了
@ECHO OFF
SETLOCAL
CALL :get_path "C:\test\a.txt"
GOTO last
:get_path
:: get file path
SET _path=%~p1
:: get file name and extension
SET _name=%~nx1
:: remove trailing backslash from path
SET _path=%_path:~0,-1%
:: trim path
CALL :trim_path %_path%
:: output
ECHO %_path% %_name%
GOTO :eof
:trim_path
:: get file name from a path returns the last folder
SET _path=%~n1
GOTO :eof
:last
ECHO ON
回答by Vlad
Based on @deStrangis' answer, here's the solution I came up with:
根据@deStrangis 的回答,这是我想出的解决方案:
##代码##