Windows命令行字符串解析:字符串中的文件夹和文件名

时间:2011-07-06 11:59:53

标签: windows batch-file cmd

是否有一种快速方法可以从Windows命令行中的完整文件路径(字符串)中获取文件名和最后一个文件夹?

我希望输入 - >结果:

"c:\test\1\2\test.txt" -> "2", "test.txt"  
"c:\test\1\2\3\a.txt" -> "3", "a.txt"  
"c:\test\0\b.txt" -> "0", "b.txt"  
"c:\c.txt" -> "", "c.txt"

我一直在使用FOR / F敲打我的头,但由于完整路径可以是任何长度,我无法理解。

3 个答案:

答案 0 :(得分:5)

试试这个:

for %I in (c:\test\1\2\3\a.txt) do set path=%~pI
for %I in (c:\test\1\2\3\a.txt) do set file=%~nxI
set pth2=%path:~0,-1%
for %I in (%pth2%) do set lastdir=%~nxI
echo %file% %lastdir%

Windows Command Line Reference是你的朋友。

答案 1 :(得分:4)

如果路径被颠倒了,那么FOR / TOKENS会起作用吗?

echo off
set apath=c:\test\1\2\3\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:

有关

File: a.txt
Dir:  3

答案 2 :(得分:0)

基于@ deStrangis'回答,这是我提出的解决方案:

@ECHO OFF
SETLOCAL

CALL :get_path "C:\test\1\2\3\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