Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate all files in a directory using a 'for' loop

How can I iterate over each file in a directory using a for loop?

And how could I tell if a certain entry is a directory or if it's just a file?

like image 242
Vhaerun Avatar asked Sep 26 '08 09:09

Vhaerun


People also ask

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do you loop a directory in Linux?

We use a standard wildcard glob pattern '*' which matches all files. By adding a '/' afterward, we'll match only directories. Then, we assign each directory to the value of a variable dir. In our simple example, we then execute the echo command between do and done to simply output the value of the variable dir.


2 Answers

This lists all the files (and only the files) in the current directory:

for /r %i in (*) do echo %i 

Also if you run that command in a batch file you need to double the % signs.

for /r %%i in (*) do echo %%i 

(thanks @agnul)

like image 152
jop Avatar answered Oct 02 '22 20:10

jop


Iterate through...

  • ...files in current dir: for %f in (.\*) do @echo %f
  • ...subdirs in current dir: for /D %s in (.\*) do @echo %s
  • ...files in current and all subdirs: for /R %f in (.\*) do @echo %f
  • ...subdirs in current and all subdirs: for /R /D %s in (.\*) do @echo %s

Unfortunately I did not find any way to iterate over files and subdirs at the same time.

Just use cygwin with its bash for much more functionality.

Apart from this: Did you notice, that the buildin help of MS Windows is a great resource for descriptions of cmd's command line syntax?

Also have a look here: http://technet.microsoft.com/en-us/library/bb490890.aspx

like image 35
Marco Avatar answered Oct 02 '22 19:10

Marco