Jim's Blog Ramblings about novels, comics, programming, and other geek topics

1May/08Off

How to write a DOS batch file to loop through files

Google AdSense

I used to write DOS batch files like this all the time, but after a while you start to forget the DOS syntax and the tricks. So this post is almost for as much for me as it is for anyone searching for how to do this.

The goal is to create a DOS batch file that can loop through a set of files and call another batch file or executable and pass the filename as the argument.

In this example, I'm going to use two (2) batch files, but in your real world solution, the second batch file might be an executable (.exe).

Let's examine the syntax of the DOS "for" command:

FOR %variable IN (set) DO command [command-parameters]

%variable  Specifies a single letter replaceable
           parameter.
(set)      Specifies a set of one or more files. 
          
Wildcards may be used.
command    Specifies the command to carry out for each
           file.
command-parameters
           Specifies parameters or switches for the
           specified command.

In addition, you can use "FOR /D", "FOR /R", and "FOR /F". The /d instructs the command to only return directories, the /r indicates recursive, and /f only returns files (in case a directory name and filename both meet the set pattern matching).

So we'll create our first DOS batch file (dubbed "doit.bat") with the below syntax:

for /f %%a IN ('dir /b *.txt') do call runner.bat %%a

In this for statement, we use the /f flag to only return filenames. Our variable name will be "%%a" and our set command will be "dir /b *.txt". This set command returns a bare directory listing (no filesize, attributes, etc. just filenames) that match the *.txt pattern. You could also include the full directory path here, just in case this DOS batch file isn't located in the same directory as your txt files. Finally we do a "do call" to tell the program to call our second batch file (runner.bat).

One neat trick is that you can parse out the filename without the extension and the extension as two (2) separate variables by changing the command to something like this:

for /f %%a IN ('dir /b *.txt') do call runner.bat %%~na %%~xa

The above loop passes the filename (without extension) as argument 1 and the file extension (".txt" in this case) as argument 2. This is done by using the "~n" and "~x" variable enhancements.

Now, in runner.bat (our second file), we can read in the arguments by using %1 and %2 where %1 is the first argument (only argument if we use the first example) and %2 as the second argument.

To test, we can write out the data such as:

echo %1-test%2

This would return the filename with the "-test" string inserted before the file extension and after the filename.

You can learn more by just opening up your command window and typing "help for".

References:

My Related Posts: , ,

James Welch

James Welch is a software engineer in Vermont working for a large information technology company and specializing in .NET. Additionally, he holds a Master’s Degree in Software Engineering and a Bachelor of Science Degree in Computer Science. Jim also enjoys local craft beer, comic books, and science-fiction and fantasy novels, games, and movies.

Twitter Google+ 

Comments (75) Trackbacks (1)
  1. Dan would be proud

  2. Thanks. It’s been at least 10 years since I’ve played with DOS. This set of instructions helped refresh me.

  3. It is behaving weird with a subdirectory. Let me explain…

    I have the following on a production server:
    c:windowsservices
    c:windowsservicesbin

    I have a deploy directory:
    DirectoryDeploy
    DirectoryDeployfiles
    DirectoryDeployfilesbin

    I want to create a .bat that lives in DirectoryDeploy and that does:

    foreach (file in DirectoryDeployfiles)
    if (fileName exists in c:windowsservices)
    copy (fileName, “DirectoryTemp”)

    foreach (file in DirectoryDeploy
    filesbin)
    if (fileName exists in c:windowsservicesbin)
    copy (fileName, “DirectoryTempbin”)

    So, I have a production directory and a deploy directory. I want the .bat to go throught the deploy directory and make a backup of any file with the same name in windowsservices.

    With this, and based on this nice posting above, I came up with:

    cd files
    for /f %%a IN (‘dir /b *.*’) do copy c:windowsservices%%a c:TEMP%%a

    cd bin
    for /f %%a IN (‘dir /b *.*’) do copy c:windowsservicesbin%%a c:TEMPbin

    My thinking…and I have no idea how you guys got ANYTHING done in the DOS days, so please be kind :)…tell the cmd to go to the file directory, compare the files here to the windowsservice directory and make backups where needed. Tell cmd to go to bin directory and do the same thing.

    It does not do this, however. When I just execute:
    cd files
    for /f %%a IN (‘dir /b *.*’) do copy c:windowsservices%%a c:TEMP%%a

    I get everything as expected in TEMP, however I also have the entire contents of windowsservicesbin copied to TEMPbin. I have looked at help dir and can’t figure out how to tell it “only copy files, don’t copy directories” because I will go through the directories and pull what I want.

    Man…do I hope this makes sense but I despise “My code won’t compile, what’s wrong” posts and I am trying to be detailed as possible and put in all the details.

    Thanks!!!

  4. this would need to exist first:)
    C:DirectoryTempbin

    files
    for /f “delims=” %%A in (‘dir/b/a-d C:DirectoryDeployfiles’) do (if exist “C:windowsservices%%A” copy “C:windowsservices%%A” “C:DirectoryTemp”)

    bin
    for /f “delims=” %%A in (‘dir/b/a-d C:DirectoryDeployfilesbin’) do (if exist “C:windowsservicesbin%%A” copy “C:windowsservices%%A” “C:DirectoryTempbin”)

  5. I have a similar problem that i can’t get my head around. I have a folder that contains a number of sub folders. Each sub folder contains a number of .txt files. I need a batch file to concatenate the files in each sub folder. Here is an example of the file tree:

    topfolder/
    topfolder/subfolder1/
    topfolder/subfolder1/text1.txt
    topfolder/subfolder1/text2.txt
    topfolder/subfolder1/text3.txt
    topfolder/subfolder2/
    topfolder/subfolder2/text1.txt
    topfolder/subfolder2/text2.txt
    topfolder/subfolder2/text3.txt

    I need the script to output one file per sub-folder:
    topfolder/subfolder1/concat.txt
    topfolder/subfolder2/concat.txt

    So far i have worked out how to concatenate files in a directory using:
    FOR %f IN (*.txt) DO TYPE “%f” >> concat.txt
    and recursively move thru the directory tree using something like:
    FOR /R %filLoc% %x IN (.) DO <> %x

    But when i try to combine the two concat.txt reports either the file name or complains about ‘system cannon find the path specified’.

    I’m new to programming and any help would be greatly appreciated. Especially some example code :D

    Thanks,
    Mandy

  6. I think that is because when you are looping, the %f only stores the filename, so it doesn’t know the directory name.

    You’ll need to include the directory name in as part of your filename or do a change directory (“cd”) command before you do your concatenation.

  7. Mandy you need to adjust the paths so they actually match. If you will be using this from the command line instead of a batch use a single percent symbol.

    for /f “delims=” %%a in (‘dir/b C:topfoldersubfolder1*.txt’) do type %%a >> “C:topfoldersubfolder1concat.txt”
    for /f “delims=” %%a in (‘dir/b C:topfoldersubfolder2*.txt’) do type %%a >> “C:topfoldersubfolder2concat.txt”

  8. I had to read the help for “for” about 7 times but i finally figured out adding the tokens option with an asterisk will capture long filenames with spaces

    example:

    for /f “tokens=*” %%A IN (‘dir /b *.txt’) do whatever

    maybe there’s a better way, but this is the first and only solution i’ve figured out…

  9. @baser5nature
    echo You are a legend :)
    … and everyone else here.

    I’m making a batch to copy some saved variables for World of Warcraft and could’nt figure out how to get the keybinding file to copy to an unspecified folder (server name) with spaces. Awesome ;)

  10. this is what i used by the way…

    FOR /F “tokens=*” %%a IN (‘DIR /B /AD “%inpath%Account”‘) DO (COPY /B “%HOMEDRIVE%AddOnPackWTFAccount!NAME!bindings-cache.wtf” “%inpath%Account%%abindings-cache.wtf”)

  11. is there any way in batch script to concat all the file names in the same batch file.
    I tried to create variable using set but its not working .

    set TEMPDIR =%LIBDIR%
    for /r %LIBDIR% %%X in (*.jar) do set TEMPDIR =%TEMPDIR%;%%X

    set TCLASSPATH=%CD%build;%LIBDIR%*.jar
    what I want to do is
    create class path by concatenating all jars under the library directory.

    Please help me to find solution to this problem
    Thanks in advance
    Vikram

  12. Vikram,

    I blogged about that a couple days after this post.

    see How to set variables in a DOS for loop

    -Jim

  13. Thanks Jim .
    It worked .But have you tested this on older Windows versions. like 2000 and and before that.

  14. I haven’t tested it in previous versions of Windows. Just Win XP. I think it’s the same syntax for all of the MS DOS versions (I think after DOS v6 or whatever, it’s been too long since I needed to remember DOS versions).

  15. Hello jim,
    I’m having some trouble with some batch I made based on this post.PLEEEEEASE HELP!!

    here goes the batch
    ———————————-
    javac %1
    for /f %%a IN (“%1″) do echo “”>%1.html
    pause
    ————————————

    it works fine when called from commandline,however when I try to drag and drop files in windows explorer it gets weird

    as you can see it gets a java file,compiles it into a class file and creates an html file to display the applet

    but when I try drag and drop,it just substitutes “java”(which is the extension of course) for %%~na instead of the file name

    help!!

  16. I don’t know about dragging and dropping files onto a DOS batch file. You might want to create a test batch file that just echos out the filename or arguments that is passed to it, when you drop a file on it. That way you can debug testing the batch file without having it mixed in with actual real functional coding.

  17. errrr

    I don’t even know the parameters to search for.
    I’m a win98 guy,I know DOS but just not that well :D

  18. how do i call a exe n times in a loop
    and pass parameter to that exe.

    I am a begginer with this and this may be a trivial question to the forum users, kindly help.

    Thanks

  19. @Guru

    it’s simple

    —————————-
    @echo off
    for /L %%I in (1,1,3) do dir/N “C:”
    —————————-

    replace (dir/N “C:”) with your program and parameters and replace 3 with the number of times you want to execute the command

  20. Howto:
    Not screw around for hours trying to get one of these commands to work correctly…

    Download and use the forfiles command instead. It has options for automatic recursing, file masks and even dates and its free too.

  21. Wow, I had no idea the DOS command line allowed such complex programming :)
    Thanks for sharing.

  22. is it possible to just read one line at a time and execute it with variable. this is what i used in unix. wonder if dos can do the same thing.

    for i in `cat file.txt` (read line and assign to variable $i)
    do
    command $i
    done

    will loop till end of line.

    thanks.

  23. I am new to this area and I am working on some batch file.
    I want to read name from some text file. Let me explain it
    I have one file File.txt, which has entry like Name=John.
    Now my batch file should read Name and I can store John in some variable.

    with following code, I can get Name stored in some variable but not John

    for /F “delims==” %%I in (File.txt) do set Title=%%I
    echo %Title%

    M

    • Mike, that’s the same problem that nigel commented about. Take a look at the stackoverflow link in my previous comment.

  24. Jim,
    That is very good link indeed.
    I can very well read first line with my code, which can give me
    “Name=John”… or if I use “delims==” in my For loop I can retrieve “Name” and store in some variable (Tile in my code). But Is there any way where I can get “John” from my File.txt and store it with in my For loop ?

    I am working on Batch file first time.. I would appreciate if you could send me a link, where I can graduate myself on this.

    Mike

  25. Mike,

    I’m not familiar with reading contents of txt files using batch scripting. If I were in that situation, then I’d just use a programming or scripting language (like C#, VB.NET, Python, Java, etc.).

    There’s not a lot of links about this. I’d think that above link to the stackoverflow might be the best resource. Maybe you can just post your question there and get it answered.

  26. i had to process each file so i leveraged Jim’s code –

    @echo off
    for /f %%x in (‘dir /b as*’) do call miok.exe %%x > %%x.txt

    works sweet.

    thanks dude.

  27. Thanks a lot!

  28. Dude, this was way helpful in doing my lazy IT guy’s job for him. Self-sufficiency FTW! Thanks!

  29. What if the file names have spaces in them?

    • You can use the DOS name of the file (the name that has the tilde “~” symbol in it) or try to use quotes around the entire path.

  30. OK, so this may not be the place to ask this, but it does relate. I am writing a DOS batch file to perform a few different things, which I have successfully created. Now, I would like to modify it so that it can be reusable. I have several variables that I would like to store together in one file. Then, I would like to have the batch file parse that file to get the values to pass on to the variables. Make sense? Can anyone help me? Thanks.

  31. I am having trouble with the following routine. Maybe someone can help. I have a file that contains a list of IP addresses for PCs that I want to copy files to. I want to loop through that file, but do not want to copy to a path that does not exist. So within the loop I send the output of a ping command to a file, then check that file for a particular string. The code logic works, but for some reason the “set pc_status” command does not set anything. It is always the same.

    For /F %%S in (%base_IP%%RDA_Source_Path%IP_List.txt) do (

    ping %%S > pingout.txt

    FOR /F %%a IN (‘more pingout.txt ^| findstr /C:”Request timed out.” /B’) DO (
    set pc_status=off
    )
    FOR /F %%a IN (‘more pingout.txt ^| findstr /C:”Reply from %%S:” /B’) DO (
    set pc_status=on
    )
    IF %pc_status%==on (
    echo COPYING FILES
    xcopy %base_IP%%RDA_Source_path%rdaFile1.txt %base%%%S%RDA_Target_path% /Y /F /R /V
    )
    echo %%S is %pc_status%
    echo FINISHED %%S
    )

  32. Just a quick glance but try something like this

    For /F %%S in (%base_IP%%RDA_Source_Path%IP_List.txt) do (
    ping %%S | find /i “reply from”
    if errorlevel 1 (
    set pc_status=on
    ) else (
    set pc_status=off
    )
    echo COPYING FILES
    xcopy %base_IP%%RDA_Source_path%rdaFile1.txt %base%%%S%RDA_Target_path% /Y /F /R /V
    )
    echo %%S is %pc_status%
    echo FINISHED %%S

  33. In the Past I’ve found it easier using the command shell in W2K and above to just string together variables something like

    Command line version:

    for /l %a in (1,1,254) do for /l %b in (1,1,254) do ping 10.%a.10.%b

  34. Thanks, got me over the line!

  35. i have question: i need to copy one file to miltiple folders using batch file can someone help please

  36. Can some one please help me in creating a batch file which will do the following command.

    C:xe_temp>OracleXE.exe /s /f1″c:xe_tempOracleXE-Install.iss” /f2″c:xe_tempsetup.log”

    • Raghu,

      Looks like you’ve already have the batch file written. Just save that command into a text file and change the file extension to .bat.

  37. Not sure if I should be posting here, but it’s worth a shot. I need a batch file that will check for a running process. If the process is running, nothing happens. If it is not running, it needs to be started. I found an example of how this could be done.

    tasklist /FI “IMAGENAME eq wordpad.exe” /FO CSV > process.log

    FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end

    start wordpad.exe

    :end

    del process.log

    The problem is the process.log file size will never be 0. If the process is running it will say:

    “Image Name”,”PID”,”Session Name”,”Session#”,”Mem Usage”
    “wordpad.exe”,”3996″,”RDP-Tcp#22″,”1″,”6,600 K”

    If the process is not running it will say:
    INFO: No tasks are running which match the specified criteria.

    How can I work off the text in the process.log file to determine my next step?

  38. Jim, I saw your example to loop through files. I modified your example thinking I could recursively loop through files and call a program to format some XML request files – in nested subfolders.

    Here is what I did:

    for /f %%a IN (’dir /b *.xml’ /s) do call formatXML.exe %%a

    This works for the first subfolder but that is it. When it ‘errors’ it appears to be passing the folder name to the ‘formatXML.exe’ as the first paramater – rather than an xml file.

    Do you know how I can get around this?

    Thanks.

    Jeff

  39. Jeff, I think it’s because you have the /s flag which is including subdirectories. I think you need to move that next to the /b flag of the dir command rather than outside of the quoted command.

  40. Jim, you are correct that my syntax was incorrect. When I changed the batch code to the following:

    for /f %%a IN (‘dir /b /s *.xml’) do call formatXML.exe %%a

    I am still receiving the same problem as described above. Seems I get through the first folder (formating several xml files) then I’m passed a directory/folder name and the formatXML.exe fails.

    Any idea how I prevent the directory/folder from being passed to my ‘called’ exe?

    Thanks.

    Jeff

    • Jeff,

      I think you can create two different loops. The first loop would loop through the folder structure. The second loop would go through each file in the directory and call your executable. An alternative would be to find a “dir” command switch that suppresses folder names and include that in your /b /s switches.

  41. hello and good day
    can someone help me with my batch file
    i managed to patch up commands from googling and came up with a bat file that scans all available drives for a specific filename, then it deletes the file and task kills a specific exe. (runs on XP and Vista)
    here it is

    @echo off & setlocal enableextensions enabledelayedexpansion
    :: Determine available fixed drives
    set drives=
    if exist “C:Drives.txt” del “C:Drives.txt”
    for /f “usebackq tokens=1*” %%a in (`fsutil fsinfo drives ^| find “:”`) do (
    if /i “%%a” NEQ “Drives:” (
    set “drives=!drives! %%a”
    echo:%%a >> C:Drives.txt
    ) ELSE (
    set “drives=!drives! %%b”
    echo:%%b >> C:Drives.txt
    )
    )
    for /f “tokens=*” %%d in (‘type “C:Drives.txt”‘) do (
    fsutil fsinfo drivetype %%d | find /i “Fixed” >nul
    if not errorlevel 1 (
    echo searching for “%file%” on drive “%%d” …
    call :SEARCHIT %%d
    )
    )
    :: Search and delete the file if found
    :SEARCHIT
    pushd %*
    for /f “tokens=*” %%f in (‘dir “test.txt” /b /s /a-d 2^>nul’) do (
    del “%%f” /f /s /q
    taskkill /f /im test.exe
    if not errorlevel 1 (
    echo “%%f” pawned
    ) else (
    echo: restarting scan for “%%f”
    )
    )

    my problem started when i add these:

    ping -n 15 localhost >nul
    cls
    goto loop (added :loop after the echo off etc.etc)

    i needed the ping and loop command to restart the batch file every 15 seconds. However, after adding those commands, the bat file only scans the rootdrive, wherein if those commands are removed, the file scans all drives. I badly needed those commands but i dont know how to properly use them ( and the proper syntax)

    thanks a bunch!

  42. I need to write a batch fiel that will loop thru a directory structure and execute an executable in each subdirectory. Each subdirectory had the same name just incremented by one digit. That is sub1, sub2, sub3.

    Thanks

  43. This method of grabbing all the files in a dir and doing something to each is just what I was looking for. I was trying to do everything in the first(single) file with no luck.

    Thanks for sharing

  44. Please could someone help me?

    I’m trying to delete all files but the first 31 of a “prova” directory (delete the 32th, 33th, 34th, etc…)

    I used this command in the XP prompt and works:

    for /F “tokens=* skip=31 delims=” %a in (‘dir /B /N /ON “C:Documents and Settingsuel1421DesktopSalvataggioprova”‘) do del prova%a

    Copying it into a .bat file doesn’t work… Why????
    (notice that the .bat file is in “C:Documents and Settingsuel1421DesktopSalvataggio” so “prova” directory should be found when running the .bat)

    Can’t see the error either putting a pause after the command, the prompt opens and suddenly closes without letting me read the error.

    Also tried replacing %a with %a%, %%a, %var%, %%var, %var but doesn’t work.

    And also tried cd “C:Documents and Settingsuel1421DesktopSalvataggio” before the command but doesn’t work.

    Thank you for helping me.
    A. G.

  45. Done.

    Don’t know why but replacing %a with %%a wasn’t accepted.

    Replaced with %%d and worked. :)

  46. Hi,
    Please help me with the batch file command.

    I am trying to convert the files from one format to another format. (i.e from .txt to .pdf) .
    ox.exe is my executable file. and it will except an o/p file name. (so, how to append that info?)

    And i want the o/p file names to be of the same input file names except with the extensions.
    i.e 1.txt –> 1.pdf
    2.txt –> 2.pdf etc…

    for /f %%a IN (‘dir /b *.txt’) do call ox.exe %%a

    I tried the above command, but i don’t know the later half of the output.

    SO, Guys, please help me out.

  47. Try something like this:

    for /f %%a IN (’dir /b *.txt’) do call ox.exe %%a %%~na.pdf

    The %%~na is the filename without the extension (so just 1, 2, etc.).

  48. really helpful for automating some repetitive tasks – splitting up the filenames was easy after reading your post!

  49. Hi,

    I’m trying to accomplish the following scenario:

    List all files that match a pattern along with a number, for ex.

    1 file_a.txt
    2 file_b.txt
    3 file_c.txt

    and then be able to pick a file by it’s number rather then it’s name.

    For this purpose I need to increment a numeric variable inside the loop and I can’t get this to work.

    Some help would be greatly appreciated.

    ——————————————————————

    @echo off
    set cnt=0

    for %%f in (*.txt) do (
    set /a cnt+=1
    echo %cnt% %%f
    )

    set cnt=0
    set /p myChoice=”Choose file: ”

    for %%f in (*.txt) do (
    set /a cnt+=1
    if cnt==%myChoice% echo %%f
    )

  50. I’m working on a batch file that calls a program to watermark photos. Using the basic:

    for /f “tokens=*” %%a IN (‘dir /b *.jpg’) do echo %%a | call runner.bat “%%a”

    This works great, until I run into a filename with a “^” in it. With a file called “noah^s art.jpg”, the “runner.bat” file:

    echo %1

    “P:Program FilesImageMagick-6.5.7-3composite.exe” -gravity southeast “copyw.bmp” %1 xxx%1

    returns:

    echo noah^^s art.jpg

    Of course, ImageMagick yells at me because there’s no such file as “noah^^s art.jpg”

    I have no idea why it’s duplicating the ^ character. Putting an echo in the “doit.bat” file returns the correct “noah^s art.jpg” Other tested special characters: [ ] ( ) – _ all worked ok.

    Any ideas? Not only to figure out the ^, but also what other special characters might be affected so I can test everything before running this on 20,000 photos.

    Thanks.

    • Can you use the switch on /dir to output DOS 8.3 (shortened) filenames and use those names? I think the 8.3 filenames won’t use special characters (other than the tilde ~).

  51. I can’t do that because I code the filename with the date, photo number, and one or two word description. I’d rather stop using the evil characters. (If worse comes to worse I can run a batch rename to replace the ^ with a temporary character, run this batch file, then run another rename to put the ^ back. It’s not like I’m going to do this more than once – I hope!)

    • I’m not asking you to change your file names. All files are stored using the 8.3 name and the longer names are displayed by the OS. You can use the hidden (real) 8.3 filenames by adding a switch to the dir command. You can access the file by it’s 8.3 or long names, it’s still the same file. The filename is just a reference pointer to the place on the disk.

      If you do a “dir /x”, then you’ll see both the short (8.3) and long filenames. You need to somehow combine that switch with the “/b” switch, but I don’t see an easy way. Otherwise, you’ll need to use “dir /x” and parse out the filenames from the list of information.

  52. Hmmm. Interesting. I figured if I used the 8.3 filename and saved it using the 8.3 filename, the system would assume I wanted the file renamed to the short filename and discard the long one. I’ll give it a try – that would be the best solution if it worked. I’ll let you know.

  53. I tested it using dir /x tokens=5 to get the short filename and it worked ok, except that the short filename was “noah^s.jpg”, still with the ^ and it came over to runner.bat as NOAH^^S.JPG.

  54. Hello

    I want to create batch file that output should be get all file names from a specified folder to a text file or a excel file

    Thanks in advance

  55. What if the file in directory is having spaces in their name. Then
    for /f %%a IN (‘dir /b’) do call echo %%a

    just prints first word of filename. How can i get full file name?

    Thanks,
    -anudeep.

  56. Your solution works like a charm. Appreciate your article James.

  57. I need to convert result.xml files to result.html file using a java plugins. I’m able to do so using command prompt.

    My problem is that i have many result.xml file in many subfolder.

    Example,
    c:project
    c:project1result.xml
    c:project2noresult.xml
    c:project3result.xml

    I have tried using the FOR command but i failed.

    for /r %%1 in (result.xml) do (convertxmltohtml)

  58. I have a directory tree that is on a student information system server. Each student has a designated folder inside this tree the path is something like this..

    student01111

    Inside the innermost folder is one file called ph.jpeg, which is the student’s picture. I need to make a copy of that picture in the same directory and call it thumb_ph.jpeg in order for the student’s picture to show up as a thumbnail on other pages in the system. The problem is, on the second tier of the tree there are 100 folders (00 – 99) and inside each of those are a bunch of student folders. I have figured out how to recurse through the tree and make a copy of each file, but the copy is always created in the root directory where the batch is located. So it writes the thumb_jpeg file in the same directory over and over until it loops through every folder.

    I have something like this…

    for /r %%f in (*.jpeg) do (copy ph.jpeg thumb_ph.jpeg
    for /r %%g in (*.jpeg) do (copy ph.jpeg thumb_ph.jpeg
    for /r %%h in (*.jpeg) do (copy ph.jpeg thumb_ph.jpeg
    )
    )
    )

    Any ideas anyone?

  59. Correction… typo in the path..
    there are 3 folder levels, not 2

    student01111
    student 011245
    student29875

  60. I just want to create a batch file that will take the current date and create a directory using the date. However, ‘/’ is not a valid character in a directory name. So how do I replace the ‘/’ with ‘-‘?
    ex: dave=%date%
    echo %dave% :: It give me the date.
    :: What do I do here to get rid of the ‘/’?

    Thanks!

    • Here’s how I do it:


      FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
      FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
      FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
      FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
      SET date=%yyyy%%mm%%dd%
      echo %date%

      At that point, you can play with the individual variables to get whatever date you want. I use YYYYMMDD since it’s sortable. You could use something like YYYY_MM_DD if you wanted by just changing it to %yyyy%_%mm%_%dd%, etc.

  61. Dave

    I use the following batch file to backup my eventlogs on a server as you can see I strip the current date out of the file and use it to not only make a directory but to rename the log files. hope that helps

    @echo off
    set ydate=%date:~-4%
    set mdate=%date:~4,2%
    set ddate=%date:~7,2%
    set bkdate=%mdate%-%ddate%-%ydate%
    md h:test%ydate%%mdate%%ddate%
    call H:Scripts”VB Scripts”evtlogbk.vbs
    for /f “Tokens=1,2 delims=.” %%a in (‘dir /b /a-d h:test’) do move /y h:test%%a.%%b h:test%ydate%%mdate%%ddate%%bkdate%%%a.%%b

  62. Jason,

    did you try looking at something like this?

    for /f %%a in (“dir /b /s /ad”) do copy %%aph.jpeg %%athumb_ph.jpeg

    It should recurse the directories giving only a list of directories and copy the file

  63. Dave

    I use the following batch file to backup my eventlogs on a server as you can see I strip the current date out of the file and use it to not only make a directory but to rename the log files. hope that helps

    @echo off
    set ydate=%date:~-4%
    set mdate=%date:~4,2%
    set ddate=%date:~7,2%
    set bkdate=%mdate%-%ddate%-%ydate%
    md h:test%ydate%%mdate%%ddate%
    call H:Scripts”VB Scripts”evtlogbk.vbs
    for /f “Tokens=1,2 delims=.” %%a in (‘dir /b /a-d h:test’) do move /y h:test%%a.%%b h:test%ydate%%mdate%%ddate%%bkdate%%%a.%%b

    It uses the set command for you date with
    ydate being year
    mdate being month
    ddate being day

    once the variables are set you can use them however you like

  64. I’m brand new to batch files, but i have a problem where i need to run through a specific folder and all its subfolders. This is what i have already

    for /R D:NewTest %%a in (“*.wmv”) do asfbin -i “%%a” -o “Reindexed-%%~na.asf” -forceindex

    Now this works, although the output is in D:NewTest and i would rather have it in the same directory as the original file.
    So how do i get a variable for the current directory i can use?

    Oh and happy new years :-)

  65. I knew this was possible, but it has been a while since I have programmed in DOS. But I find it so useful at times, so when I needed a refresher, this article came up first. Thanks, it’s great to see that such a convenient and simple, yet versatile “programming language” is still in use!

  66. Kim,

    Have you tried using %%~fa instead of %%~na?