M BUZZ CRAZE NEWS
// general

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

By Joseph Russell

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
2

1 Answer

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
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy