Impostor
Impostor

Reputation: 2050

Iterate files by extension and substring search

I have this code

for /R "C:\myfiles" %%i in (*super*.ts) do (
echo %%i
)

so I want to iterate over all files in the folder C:\myfiles which have in the path super and end with .ts. e.g.

"c:\myfiles\foo\bar\super\123.ts"

but that substring search doesn't work.

Upvotes: 0

Views: 109

Answers (2)

Dominique
Dominique

Reputation: 17479

What about this:

dir /S /B C:\myfiles\*.ts | findstr /I "Super"

Explanation:

dir /S : search in subdirectories
dir /B : show bare format, like C:\myfile\subdir\filename.ts
...
findstr /I : filter is case insensitive

result:

for /f "delims=" %%a in ('dir /S /B C:\myfiles\*.ts ^| findstr /I "Super"') do echo %%a

Upvotes: 3

aschipfl
aschipfl

Reputation: 34909

Your for /R loop searches for files whose names contain super, but that is not what you want.

If one of the following situations apply, you could use below code snippets:

  1. If the word super may occur anywhere in the path, even in the file name:

     for /F "delims=" %%F in ('
         dir /S /B /A:-D-H-S "C:\myfiles\*.ts" ^| findstr /I /C:"super"
     ') do (
         echo(%%F
     )
    

    The /A:-D-H-S option of dir excludes directories as well as hidden and system files.

  2. If the word super is the name of any directory in the hierarchy:

     for /F "delims=" %%F in ('
         dir /S /B /A:-D-H-S "C:\myfiles\*.ts" ^| findstr /I /C:"\\super\\"
     ') do (
         echo(%%F
     )
    

    The \\ in the findstr search expression constitutes an escaped \.

  3. If the word super is the name of the immediate parent directory:

     for /F "delims=" %%F in ('
         dir /S /B /A:-D-H-S "C:\myfiles\*.ts" ^| findstr /I /R /C:"\\super\\[^\\][^\\]*\.ts$"
     ') do (
         echo(%%F
     )
    

    The string \\super\\[^\\][^\\]*\.ts$ is a findstr regular expression, that anchors to the right ($) a string that consists of the literal string \super\ plus a string of at least a character other than \ and the literal string .ts.

    And here is an alternative approach without findstr but an if statement instead, together with a standard for loop to resolve the name of the parent directory:

     for /R "C:\myfiles" %%F in (*.ts) do (
         for %%E in ("%%~F\..") do (
             if /I "%%~nxE"=="super" echo(%%~F
         )
     )
    

    This may be faster, because there is no for /F and no pipe (|) involved, both of which instantiate new cmd.exe instances.

Upvotes: 2

Related Questions