【问题标题】:How do I shorten file path output to text files in batch files如何将文件路径输出缩短为批处理文件中的文本文件
【发布时间】:2023-03-27 12:05:01
【问题描述】:
@echo off
REM - Check to see if there are any non-school related files on the system (mp3, jpg, png, exe)
REM - And print them out #bigbrother1984

cd G:\Assign2\

FOR /F "tokens=*" %%G IN ('dir /s /b "G:\Assign2\*.mp3"') DO echo %%G >> Found_MusicFiles.txt

FOR /F "tokens=*" %%G IN ('dir /s /b "G:\Assign2\*.JPG"') DO echo %%G >> Found_ImageFiles.txt

FOR /F "tokens=*" %%G IN ('dir /s /b "G:\Assign2\*.PNG"') DO echo %%G >> Found_ImageFiles.txt

 FOR /F "tokens=*" %%G IN ('dir /s /b "G:\Assign2\*.exe"') DO echo %%G >>  Found_GamesFiles.txt

例如,这会在 Assign2 下找到 .mp3、jpg、png、exe 文件,并打印出它找到的结果。 但它会像这样打印出来 G:\Assign2\blah\blah\blah\blah\blah\Game.exe

我希望它打印出 \blah\game.exe 之类的东西

有什么想法吗?我尝试使用 %~nI,但我不知道如何使用它并且是批处理新手。

【问题讨论】:

  • 你想要相对路径?
  • 或者你想在你的for循环中使用%%~nG
  • 以“C:\USers\...”开头的示例输出与以“G:\Assign2\...”开头的脚本位置不匹配

标签: batch-file for-loop cmd dir


【解决方案1】:

这应该可以满足您的需要:

@echo off
REM - Check to see if there are any non-school related files on the system (mp3, jpg, png, exe)
REM - And print them out #bigbrother1984

pushd "G:\Assign2\"

FOR /F "delims=" %%a IN ('dir /s /b /a-d *.mp3 *.jpg *.png *.exe ') DO (
for %%b in ("%%~pa.") do >>"%userprofile%\desktop\Found_MusicFiles.txt" echo %%~nxb\%%~nxa
)
popd

【讨论】:

    【解决方案2】:

    这将适用于您进行一些小的修改:

    FOR %%a IN ("C:\USers\blah\blah\blah\blah\blah\Game.exe") do for %%b in ("%%~pa.") do echo \%%~nxb\%%~nxa
    

    【讨论】:

    • +1,非常好。但我认为 OP 在想要前导 \ 时被误导了,因为这意味着从根目录开始的绝对文件夹。
    【解决方案3】:

    Endoro 提供了一个答案,可以准确地满足您的要求。但我怀疑这可能不是你想要的。您只要求提供路径中的最后一个文件夹,但这可能不足以判断它来自哪里。

    我怀疑你想要从当前目录开始的相对路径。

    FORFILES 命令直接提供相对路径:

    cd G:\Assign2
    forfiles /s /m *.mp3 /c "cmd /c echo @relpath"
    etc.
    

    或者不需要CD

    forfiles /s /p "G:\Assign2" /m *.mp3 /c "cmd /c echo @relpath"
    etc.
    

    输出类似于".\blah\blah\file.mp3",其中. 表示您的起始位置G:\Assign2。 (换句话说,相对路径)

    【讨论】:

    • Endoro 的代码只打印一个静态文件名,并将 blah 作为父文件夹。鉴于提供的代码,这与他所要求的“完全”相去甚远。 :) Endoro 一定很忙。不过我认为你是对的——这个家伙可能也想要更多的路径信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多