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
Related videos on Youtube
![Mark Deven](https://i.stack.imgur.com/0sVza.png?s=256&g=1)
Author by
Mark Deven
Updated on September 18, 2022Comments
-
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 rundir /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 about 6 yearsOmit the
/S
If there are files in subdirs with the same name how would you distinguish them? Otherwise parse dir output with afor /f
and use the~nx
modifier to return only name+extensionfor /f "delims=" %A in ('dir /B/S "C:\WinPE_amd64"') do @Echo=%~nxA
-
Mark Deven about 6 yearsMy 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 about 6 yearsThe only problem is that this is a very slow script for a 2,000 line DIR.
-
Mark Deven about 6 yearsstill, probably the best Ill get from a batch
-
LotPings about 6 yearsParsing with
for /f
involves a second instance of cmd.exe. I add another way to the answer