如何编写批处理文件将目录下的txt文件名传递至其他命令
Batch File to Automatically Print Dynamic TXT Files in a Directory
Got it, here's a straightforward batch script that will scan your folder directory for all .txt files (including those with dynamic numeric endings like file66.txt) and run the print command for each one:
@echo off set "targetDir=folder" :: Check if the target directory exists if not exist "%targetDir%\" ( echo Error: Directory "%targetDir%" not found! pause exit /b 1 ) :: Loop through all .txt files in the directory for %%F in ("%targetDir%\*.txt") do ( echo Executing: print "%%~nxF" print "%%~nxF" ) echo All print commands completed. pause
Breakdown of the Script:
@echo off: Hides command prompts from being displayed as the script runs, keeping output clean.set "targetDir=folder": Defines the directory we're scanning (adjust this if your folder has a different name or absolute path likeC:\MyDocs\folder).- The
if not existcheck: Ensures the target directory exists before proceeding, avoiding errors if it's missing. - The
forloop: Iterates over every.txtfile in the directory.%%Fholds each file's full path, and%%~nxFextracts just the filename + extension (e.g.,file66.txt) which is what we need for the print command. echo Executing...: Prints a debug message showing which file is being processed (you can remove this line if you don't want extra output).print "%%~nxF": Runs the actual print command for each file—this is the line that generates your desiredprint fileXX.txtoutput.
Customization Tips:
- If you only want to target files starting with
filefollowed by numbers (e.g.,file12.txt,file99.txt), modify the loop line to:for %%F in ("%targetDir%\file*.txt") do ( - If your filenames contain spaces, the quotes around
"%%~nxF"ensure the command handles them correctly without breaking.
How to Use:
- Open Notepad, paste the script above.
- Save it as
PrintTxtFiles.bat(make sure to select "All Files" as the save type, not.txt). - Place the batch file in the same directory as your
folderdirectory, or updatetargetDirto use an absolute path. - Double-click the batch file to run it.
内容的提问来源于stack exchange,提问作者BB20
相关产品推荐
相关产品推荐

