-
When working with batch scripts in Windows, two often-overlooked but fundamental tools are:
-
📄 File Extensions — which determine how files are interpreted and handled
-
✳ Wildcards — which let you select multiple files dynamically
Together, they let you create powerful scripts that are flexible, dynamic, and scalable — perfect for file processing, cleanup routines, and automated workflows.
In Windows, file extensions (e.g.,
.txt,.log,.exe) define how the OS treats the file. In batch scripting:- You often filter files by extension using
FOR,IF EXIST,DEL,COPY, etc. - Extensions are not case-sensitive
- To reference just the extension or filename, use variable modifiers
Extension Use Case .batBatch script .cmdModern batch script (like .bat).txtLogs, data, or configuration .logLogs from apps or services .exeExecutables .zipArchives or backups -
-
Wildcards let you match multiple files using patterns.
Wildcard Meaning *Zero or more characters ?Exactly one character
DIR *.txt :: All files ending in .txt DIR data?.csv :: data1.csv, dataA.csv, but NOT data10.csv DEL report*.log :: report1.log, report_final.log
DEL /Q *.tmpDeletes all
.tmpfiles in the directory without confirmation.
COPY *.txt D:\Backup\Copies all
.txtfiles to the backup directory.
FOR %%F IN (*.log) DO ( ECHO Processing: %%F )
This loop processes all
.logfiles in the current folder.You can also apply filters:
FOR %%F IN (report_202?.log) DO ( ECHO Match: %%F )
FOR /R %%F IN (*.txt) DO ( ECHO Found: %%F )
- Recursively finds all
.txtfiles in current and subfolders.
- Recursively finds all
-
Inside a
FORloop, you can extract file parts:Modifier Meaning %%~nFName only (no extension) %%~xFExtension only (with dot) %%~dpFDrive + path %%~nxFName + extension FOR %%F IN (*.log) DO ( ECHO Name: %%~nF, Extension: %%~xF )
-
FOR %%F IN (*.txt) DO ( REN "%%F" "%%~nF.bak" )
-
MOVE *.zip D:\Archives\ -
SET COUNT=0 FOR %%F IN (*.log) DO SET /A COUNT+=1 ECHO Log file count: %COUNT%
-
DEL /S /Q backup_*.zipDeletes all ZIP files starting with
backup_in current and subfolders. -
You can conditionally act on file extensions:
FOR %%F IN (*) DO ( IF /I "%%~xF"==".log" ( ECHO Found log file: %%F ) )
Use
/Ifor case-insensitive comparison.
| Issue | Workaround |
|---|---|
Cannot use wildcards with REN destination |
Use FOR loop with modifiers |
Wildcards in IF EXIST require care |
Avoid quotes: IF EXIST *.txt (not IF EXIST "*.txt") |
| No regex support | Use PowerShell or hybrid script for complex filters |
| Task | Batch Pattern |
|---|---|
Match all .txt files |
*.txt |
| Match any one-letter name | ?.txt |
| Process by extension | FOR %%F IN (*.ext) |
| Get name only | %%~nF |
| Get extension only | %%~xF |