Windows command dir lists files with absolute path, relative path required

I would like to list all filesnames of all files with a specific extension in a directory structure and write this to a file. What I have reached:

dir /B /S *.ext > list.filenames

This gives me a list of all files that I want to have in the list. But it lists the files with an absolute path, including drive letter and full path. What I need to have is the relative path without drive letter and path to the working directory.

I was thinking about two possibilities but did not find a solution:

  1. Tell dir to print only relativ paths
  2. strip unneeded part of the path from the created file.

Both I was not able to achieve. Any ideas?

3 Answers

Here is a solution which calls Powershell though there are probably other better ways too:

dir /B /S *.ext > abs.filenames
set search='%cd%\'
powershell -Command "(gc abs.filenames) -replace [regex]::escape(%search%), '' " 2>&1 > list.filenames
type list.filenames

Note that Windows Powershell might not be available as it is one of the Optional Features found under Apps & Features.

Windows Subsystem For Linux or Cygwin on Windows would give you access to a lot of better tools for this task, such as with find:

find . -name \*.ext > list.filenames

You can try this:

Open PowerShell:

Win+R>>type powershell>>Ctrl+Shift+Enter

Then use these codes:

$path="path\to\folder"
(Get-ChildItem -Path $path -File -Filter "*.ext" -Force -Recurse).FullName | %{$_.Replace($path)}

Remember to replace path\to\folder with actual path, you need quotes even if the path doesn't contain spaces, and replace .ext with the actual extension.

It should give you what you want.

You can use your dir /b /s command in a For /F loop to do this already removing D:\ using tokens^=2*delims^=\ and @echo= .\ + %~J

for /f tokens^=2*delims^=\ %i in ('dir/b/s D:\Folder\*.eXt')do @echo= .\%~j >>file.txt
  • Results:
.\File_01.eXt.\File_02.eXt.\Sub_Folder_1\File_03.eXt.\Sub_Folder_1\File_04.eXt

Or, keep your \Folder... using tokens^=1* and echo= .\ + %~j

for /f tokens^=1*delims^=\ %i in ('dir/b/s D:\Folder\*.eXt')do @echo= .\%~j >>file.txt
  • Results:
.\Folder\File_01.eXt.\Folder\File_02.eXt.\Folder\Sub_Folder_1\File_03.eXt.\Folder\Sub_Folder_1\File_04.eXt
  • You can also suppress/remove the .\ from the @echo .\ command if necessary

  • For PowerShell, you can to do the same:
ls *.eXt -re|% {$_.FullName.Split(":").Get(1)}|Out-File -FilePath .\Files_eXt.txt

Or, also adding ".":

ls *.eXt -re|%{$_str='.'+($_.FullName.Split(":").Get(1));$_str}>.\Files_eXt.txt

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

You Might Also Like