如何使用 echo 从 windows 批处理文件中获取相对路径?

How do I get a relative path out of a windows batch file using echo?

如何从 windows .bat 文件获取相对目录/部分路径以显示为回显输出?

How to split the filename from a full path in batch?

无所不谈。

我找到了驱动器号、文件名、扩展名、缩短的 (8.3) 名称和完整路径 - 但没有找到相对路径。

我是运行一个递归FOR /R循环;遍历子目录。我想要一些东西 - 没有二十个字符的无用路径信息 - 告诉我每个重复文件位于哪个目录......而无需将 .bat 文件硬编码为位于某个 directory/path?

也许一个解决方案是测量脚本路径的长度并将其从完整路径的前面切掉?但我不知道如何操作它。

脚本可能位于多个位置:

F:\a.bat<BR>
F:\Dir1\fileA.txt<BR>
F:\Dir20\fileA.txt

C:\Users\Longusername\Desktop\Container\a.bat<BR>
C:\Users\Longusername\Desktop\Container\Dir1\fileA<BR>
C:\Users\Longusername\Desktop\Container\Dir20\fileA

现在我唯一的输出选项是 (%%~nxG):

fileA.txt
fileA.txt

没有告诉我每个文件在哪个目录中...或者 (%%~pnxG)

\Users\Longusername\Desktop\Container\Dir1\fileA.txt
\Users\Longusername\Desktop\Container\Dir20\fileA.txt

我想要的,来自任何位置:

\Dir1\fileA.txt
\Dir20\fileA.txt

可能缺少前导 \,但这可以忽略不计。如果 echo 可以在大多数 window 机器上工作,则其他选项也是允许的。不过,它们可能会引发更多问题 - 因为我已经用 echo 找出了我的其他作品。

很简单,如果您考虑一下:只需删除当前目录路径(%cd%):

@echo off 
setlocal enabledelayedexpansion
for /r %%a in (*.txt) do (
  set "x=%%a"
  echo with \:    !x:%cd%\=\!
  echo without \: !x:%cd%\=!
)

顺便说一下:\folder\file 总是指驱动器的根目录 (x:\folder\file),所以它不完全是相对路径。

这与已接受的答案类似,但仅在需要时启用延迟扩展。这应该正确输出包含 ! 个字符的文件名。

@Echo Off
SetLocal DisableDelayedExpansion

Set "TopLevel=C:\Users\LongUserName"

For /R "%TopLevel%" %%A In ("*.txt") Do (
    Set "_=%%A"
    SetLocal EnableDelayedExpansion
    Echo=!_:*%TopLevel%=!
    EndLocal
)

Pause

您还可以使用 Set "TopLevel=%~dp0"(运行 脚本的目录)Set "TopLevel=%~dp0.."(运行 脚本的父目录)


上述方法的一个潜在好处是您也可以使用相对于当前目录的位置作为 %TopLevel% 的值,(在这种情况下,基于初始示例, 当前目录为 C:\Users):

Set "TopLevel=LongUserName"

尽管只有当 LongUserName 不存在于树中较早的路径内容时才能正常工作。

您可以将 xcopy 与其 /S(包括子目录)和 /L(列出但不复制)选项一起使用,因为它 returns 相对路径那么,您就不必进行任何字符串操作,这有时可能有点危险,尤其是当当前目录是驱动器的根目录时:

xcopy /L /S /I /Y /R ".\*.txt" "\" | find ".\"

附加的 find command 构成一个过滤器,从输出中删除摘要行 # File(s)


要捕获上述命令行的输出,只需使用 for /F loop:

for /F "delims=" %%I in ('
    xcopy /L /S /I /Y /R ".\*.txt" "\" ^| find ".\"
') do (
    rem // Do something with each item:
    echo/%%I
)