Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch file - counting number of files in folder and storing in a variable

Tags:

batch-file

I am very new to this. Please help me

I was trying to write a batch file program to count number of files in a folder and assign that to a variable and display it to verify that it has been stored please help me with the syntax,

thank you in advance -VK

like image 843
user1452157 Avatar asked Jun 12 '12 20:06

user1452157


People also ask

Is there a way to count the number of files in a folder?

Use File Explorer Open the folder and select all the subfolders or files either manually or by pressing CTRL+A shortcut. If you choose manually, you can select and omit particular files. You can now see the total count near the left bottom of the window. Repeat the same for the files inside a folder and subfolder too.

How do I count the number of files in a subfolder?

To count all the files and directories in the current directory and subdirectories, type dir *. * /s at the prompt.

Can you use variables in batch files?

There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.

How do I count the number of files in a directory in PowerShell?

To get count files in the folder using PowerShell, Use the Get-ChildItem command to get total files in directory and use measure-object to get count files in a folder.


1 Answers

I'm going to assume you do not want to count hidden or system files.

There are many ways to do this. All of the methods that I will show involve some form of the FOR command. There are many variations of the FOR command that look almost the same, but they behave very differently. It can be confusing for a beginner.

You can get help by typing HELP FOR or FOR /? from the command line. But that help is a bit cryptic if you are not used to reading it.

1) The DIR command lists the number of files in the directory. You can pipe the results of DIR to FIND to get the relevant line and then use FOR /F to parse the desired value from the line. The problem with this technique is the string you search for has to change depending on the language used by the operating system.

@echo off for /f %%A in ('dir ^| find "File(s)"') do set cnt=%%A echo File count = %cnt% 

2) You can use DIR /B /A-D-H-S to list the non-hidden/non-system files without other info, pipe the result to FIND to count the number of files, and use FOR /F to read the result.

@echo off for /f %%A in ('dir /a-d-s-h /b ^| find /v /c ""') do set cnt=%%A echo File count = %cnt% 

3) You can use a simple FOR to enumerate all the files and SET /A to increment a counter for each file found.

@echo off set cnt=0 for %%A in (*) do set /a cnt+=1 echo File count = %cnt% 
like image 171
dbenham Avatar answered Oct 20 '22 15:10

dbenham