JohnW
JohnW

Reputation: 345

Batch Scripting - FOR and IF

Just new to Batch Scripting and having a problem here: I've been asked to list all the text files whose names are 7 letters long within the whole c:\ drive and ouput it to a file. I can't figure it out.

After endless hours of searching google I've come up with this:

for /R C:\ %i in (.\*) do if %~ni==???????.txt echo %i > file.txt

Now I understand this is probably wrong due to the fact... it's not working.

Thanks in advance. John W.

Upvotes: 0

Views: 192

Answers (2)

adarshr
adarshr

Reputation: 62583

I think this will do it. You don't really need a batch file for this.

dir /s /b C:\*.txt | findstr "\\.......\.txt$" > files.txt

Update:

To make it work for 123\123.txt use

dir /s /b C:\*.txt | findstr "\\[^\\][^\\][^\\][^\\][^\\][^\\][^\\]\.txt$" > files.txt

Upvotes: 3

jeb
jeb

Reputation: 82297

I would put the code into a batch file, then you have to double the percent signs of the FOR-Loop.
As the FOR /R supports some nice features, like searching for a file-masks, you could use this.

But ???? will find all files with a maximum of the number of question marks not only excact matching.
Therefore I test the filename later, if it has at least 7 characters

setlocal EnableDelayedExpansion
for /R C:\temp\ %%i in (???????.txt) do (
  set "filename=%%~ni"
  if "!filename:~6,1!" NEQ "" (
    echo has 7 characters %%i
  )
)

Upvotes: 0

Related Questions