Loop (files & folders)

Retrieves the specified files or folders, one at a time.

Loop, FilePattern [, IncludeFolders?, Recurse?]

 

Parameters

FilePattern

The name of a single file or folder, or a wildcard pattern such as C:\Temp\*.tmp. FilePattern is assumed to be in %A_WorkingDir% if an absolute path isn't specified.

Both asterisks and question marks are supported as wildcards.

If this parameter is a single file or folder (i.e. no wildcards) and Recurse is set to 1, more than one match will be found if the specified file name appears in more than one of the folders being searched.

IncludeFolders?

One of the following digits, or blank to use the default:
0 (default) Folders are not retrieved (only files).
1 All files and folders that match the wildcard pattern are retrieved.
2 Only folders are retrieved (no files).

Recurse? One of the following digits, or blank to use the default:
0 (default) Subfolders are not recursed into.
1 Subfolders are recursed into so that files and folders contained therein are retrieved if they match FilePattern. All subfolders will be recursed into, not just those whose names match FilePattern.

 

Remarks

A file-loop is useful when you want to operate on a collection of files and/or folders, one at a time.

All matching files are retrieved, including hidden files. By contrast, OS features such as the DIR command omit hidden files by default. To avoid processing hidden, system, and/or read-only files, use something like the following inside the loop:

if A_LoopFileAttrib contains H,R,S  ; Skip any file that is either H (Hidden), R (Read-only), or S (System). Note: No spaces in "H,R,S".
	continue  ; Skip this file and move on to the next one.

To retrieve files' relative paths instead of absolute paths during a recursive search, use SetWorkingDir to change to the base folder prior to the loop, and then omit the path from the Loop (e.g. Loop, *.*, 0, 1). That will cause A_LoopFileFullPath to contain the file's path relative to the base folder.

Files in an NTFS file system are probably always retrieved in alphabetical order. Files in other file systems are retrieved in no particular order. To ensure a particular ordering, use the Sort command as shown in the Examples section below.

The following variables exist within any file-loop. If an inner file-loop is enclosed by an outer file-loop, the innermost loop's file will take precedence:

A_LoopFileName The name of the file or folder currently retrieved (without the path).
A_LoopFileExt
[v1.0.36.02+]
The file's extension (e.g. TXT, DOC, or EXE). The dot is not included.
A_LoopFileFullPath The full path and name of the file/folder currently retrieved. However, if FilePattern contains a relative path rather than an absolute path, the path here will also be relative. In addition, any short (8.3) folder names in FilePattern will still be short (see next item to get the long version).
A_LoopFileLongPath
[v1.0.26+]
This is different than A_LoopFileFullPath in the following ways: 1) It always contains the absolute/complete path of the file even if FilePattern contains a relative path; 2) Any short (8.3) folder names in FilePattern itself are converted to their long names; 3) Characters in FilePattern are converted to uppercase or lowercase to match the case stored in the file system. This is useful for converting file names -- such as those passed into a script as command line parameters -- to their exact path names as shown by Explorer.
A_LoopFileShortPath
[v1.0.25+]

The 8.3 short path and name of the file/folder currently retrieved. For example: C:\MYDOCU~1\ADDRES~1.txt. However, if FilePattern contains a relative path rather than an absolute path, the path here will also be relative.

To retrieve the complete 8.3 path and name for a single file or folder, specify its name for FilePattern as in this example:
Loop, C:\My Documents\Address List.txt
    ShortPathName = %A_LoopFileShortPath%

NOTE: This variable will be blank if the file does not have a short name, which can happen on systems where NtfsDisable8dot3NameCreation has been set in the registry. It will also be blank if FilePattern contains a relative path and the body of the loop uses SetWorkingDir to switch away from the working directory in effect for the loop itself.

A_LoopFileShortName The 8.3 short name, or alternate name of the file. If the file doesn't have one (due to the long name being shorter than 8.3 or perhaps because short-name generation is disabled on an NTFS file system), A_LoopFileName will be retrieved instead.
A_LoopFileDir The full path of the directory in which A_LoopFileName resides. However, if FilePattern contains a relative path rather than an absolute path, the path here will also be relative. A root directory will not contain a trailing backslash. For example: C:
A_LoopFileTimeModified The time the file was last modified. Format YYYYMMDDHH24MISS.
A_LoopFileTimeCreated The time the file was created. Format YYYYMMDDHH24MISS.
A_LoopFileTimeAccessed The time the file was last accessed. Format YYYYMMDDHH24MISS.
A_LoopFileAttrib The attributes of the file currently retrieved.
A_LoopFileSize The size in bytes of the file currently retrieved. Files larger than 4 gigabytes are also supported.
A_LoopFileSizeKB The size in Kbytes of the file currently retrieved.
A_LoopFileSizeMB The size in Mbytes of the file currently retrieved.

 

See Loop for information about Blocks, Break, Continue, and the A_Index variable (which exists in every type of loop).

 

Related

Loop, Break, Continue, Blocks, SplitPath, FileSetAttrib, FileSetTime

 

Examples

; Example #1:
Loop, %ProgramFiles%\*.txt, , 1  ; Recurse into subfolders.
{
	MsgBox, 4, , Filename = %A_LoopFileFullPath%`n`nContinue?
	IfMsgBox, No
		break
}


; Example #2: Calculate the size of a folder, including the files in all its subfolders: SetBatchLines, -1 ; Make the operation run at maximum speed. FolderSizeKB = 0 FileSelectFolder, WhichFolder ; Ask the user to pick a folder. Loop, %WhichFolder%\*.*, , 1 FolderSizeKB += %A_LoopFileSizeKB% MsgBox Size of %WhichFolder% is %FolderSizeKB% KB.
; Example #3: Retrieve file names sorted by name (see next example to sort by date): FileList = ; Initialize to be blank. Loop, C:\*.* FileList = %FileList%%A_LoopFileName%`n Sort, FileList, R ; The R option sorts in reverse order. See Sort for other options. Loop, parse, FileList, `n { if A_LoopField = ; Ignore the blank item at the end of the list. continue MsgBox, 4,, File number %A_Index% is %A_LoopField%. Continue? IfMsgBox, No break }
; Example #4: Retrieve file names sorted by modification date: FileList = Loop, %UserProfile%\Recent\*.*, 1 ; UserProfile exists as an environment variable on some OSes. FileList = %FileList%%A_LoopFileTimeModified%`t%A_LoopFileName%`n Sort, FileList ; Sort by date. Loop, parse, FileList, `n { if A_LoopField = ; Omit the last linefeed (blank item) at the end of the list. continue StringSplit, FileItem, A_LoopField, %A_Tab% ; Split into two parts at the tab char. MsgBox, 4,, The next file (modified at %FileItem1%) is:`n%FileItem2%`n`nContinue? IfMsgBox, No break }
; Example #5: Copy only the source files that are newer than their counterparts ; in the destination: CopyIfNewer: ; Caller has set the variables CopySourcePattern and CopyDest for us. Loop, %CopySourcePattern% { copy_it = n IfNotExist, %CopyDest%\%A_LoopFileName% ; Always copy if target file doesn't yet exist. copy_it = y else { FileGetTime, time, %CopyDest%\%A_LoopFileName% EnvSub, time, %A_LoopFileTimeModified%, seconds ; Subtract the source file's time from the destination's. if time < 0 ; Source file is newer than destination file. copy_it = y } if copy_it = y { FileCopy, %A_LoopFileFullPath%, %CopyDest%\%A_LoopFileName%, 1 ; Copy with overwrite=yes if ErrorLevel <> 0 MsgBox, Could not copy "%A_LoopFileFullPath%" to "%CopyDest%\%A_LoopFileName%". } } Return
; Example #6: Convert filenames passed in via command-line parameters to long names, ; complete path, and correct uppercase/lowercase characters as stored in the file system. ; This script requires v1.0.25+. Loop %0% ; For each file dropped onto the script (or passed as a parameter). { GivenPath := %A_Index% ; Retrieve the next command line parameter. Loop %GivenPath% LongPath = %A_LoopFileLongPath% MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath% }