How to not show file path with dir /b /s command in batch file

5,655

Parse dir output with a for /f and use the ~nx modifier to return only name+extension

On the cmd line:

(for /f "delims=" %A in ('dir /B/S "C:\WinPE_amd64"') do @Echo=%~nxA)>dir.txt

In a batch double the percent sign of the for metavariable

@Echo off
( for /f "delims=" %%A in ('dir /B/S "C:\WinPE_amd64"') do Echo=%%~nxA
) >dir.txt

It is a matter of formatting preference (or to avoid overly long lines)

@Echo off
( for /f "delims=" %%A in (
    'dir /B/S "C:\WinPE_amd64"'
  ) do Echo=%%~nxA
) >dir.txt

EDIT a possibly faster alternative is a for /r

(For /r "C:\WinPE_amd64" %A in (*) Do @Echo=%~nxA)>dir.txt

Another alternative wrapping a powershell command

powershell -nop -c "(dir 'C:\WinPE_amd64' -r -file).Name" >dir.txt
Share:
5,655

Related videos on Youtube

Mark Deven
Author by

Mark Deven

Updated on September 18, 2022

Comments

  • Mark Deven
    Mark Deven almost 2 years

    Is there Any way I can bypass displaying file paths when using the dir /b /s command into a file?
    Currently, when I run dir /b /s C:\WinPE_amd64 >dir.txt it outputs something like this:

    C:\WinPE_amd64\file.txt
    C:\WinPE_amd64\secondfile.txt
    C:\WinPE_amd64\Folder\AnotherFile.txt
    

    What I want is something like this:

    file.txt
    secondfile.txt
    AnotherFile.txt
    
    • LotPings
      LotPings about 6 years
      Omit the /S If there are files in subdirs with the same name how would you distinguish them? Otherwise parse dir output with a for /f and use the ~nx modifier to return only name+extension for /f "delims=" %A in ('dir /B/S "C:\WinPE_amd64"') do @Echo=%~nxA
    • Mark Deven
      Mark Deven about 6 years
      My Dir Command need not distinguish them since I then sort out new and old files. That is perfect thank you. Maybe post that as an answer so you get credit
  • Mark Deven
    Mark Deven about 6 years
    The only problem is that this is a very slow script for a 2,000 line DIR.
  • Mark Deven
    Mark Deven about 6 years
    still, probably the best Ill get from a batch
  • LotPings
    LotPings about 6 years
    Parsing with for /f involves a second instance of cmd.exe. I add another way to the answer