Search code examples
batch-filefor-loopcmddir

How do I shorten file path output to text files in batch files


@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

So for example this finds .mp3, jpg, png, exe files below Assign2, and prints out the results of what it finds. But it prints them out like this G:\Assign2\blah\blah\blah\blah\blah\Game.exe

I would like it to print out something like \blah\game.exe

Any ideas? I tried using %~nI, but I don't know how to use it and am new to batch.


Solution

  • This should do what you need:

    @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