Home > Blockchain >  How to get the all directory list which directory have common directory using batch
How to get the all directory list which directory have common directory using batch

Time:08-24

I am trying to get the folder directory which have common directory using batch

I have tried but getting all directory list

for /r /d %%s in (\myfolder\*) do (
    @echo %%~fs
 )

Folder directory :

- myfolder
  - temp1
    - common_directory
  - temp2
    - common_directory
  - temp 3
   - folder_3 

I want below directory only :

- myfolder/temp1/common_directory
- myfolder/temp2/common_directory

CodePudding user response:

What about this:

forfiles /S /C "cmd /c if @isdir==TRUE echo @path" | findstr /I "common_directory"

Let me explain:

  • forfiles /S : go into subdirectories
  • forfiles /C : launch a script inside your forfiles session
    more can be found using forfiles /?
  • | findstr /I "common_directory : /I makes it case insensitive

Have fun!

P.s. According to Compo, you can avoid using Findstr using the following command:

%SystemRoot%\System32\forfiles.exe /S /P "myfolder" /M "common_directory" /C "%SystemRoot%\System32\cmd.exe /D /C \"If @IsDir == TRUE If /I @File == \"common_directory\" Echo @Path\"" 2>NUL

CodePudding user response:

This worked for me

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=u:\your files"
:: remove variables starting ?
FOR  /F "delims==" %%b In ('set ? 2^>Nul') DO SET "%%b="

for /r "%sourcedir%" /d %%e in (*) do (
IF "!?%%~nxe!"=="" (
  SET "?%%~nxe=%%e"
 ) ELSE (
 ECHO !?%%~nxe!
 ECHO %%e
 )
)

GOTO :EOF

Always verify against a test directory before applying to real data.

Simply set a variable ?leafname to the directoryname found if it's not already set, or echo the value stored and the newly-found name if it has been set by encountering the same leafname previously.

I used ? before the leafname as ? can't appear in a leafname.

  • Related