1

I have a batch file that loops through a folder, inserting a line of text into each CSV in a folder and generating a file that counts the lines of each file.

I want to also generate a subdirectory in the main folder for each CSV file, without including the ".csv" extension. The code below seems like it should work, (it works when I isolate the three lines to their own bat file!) but in the loop, it returns the same value for the folder name each iteration of the loop. How do I make the dirname variable update with the current value?

copy NUL count.txt
for %%f in (*.csv) do (
    setlocal EnableDelayedExpansion
    set "cmd=findstr /R /N "^^" %%f | find /C ":""

        for /f %%a in ('!cmd!') do set number=%%a
        echo %%f   !number!>>count.txt

        SET filename=%%f
        SET dirname=%filename:~0,13%
        mkdir %dirname%

    type header.txt >%%f.new
    type %%f >>%%f.new
    move /y %%f.new %%f
 )
  • 1
    SET dirname=!filename:~0,13! should do the trick. You need to use delayed expansion just like you did for number. – DavidPostill Jul 26 '17 at 17:40
  • 1
    Y'all wanna make the Answer and mark this as solved? – HackSlash Jul 26 '17 at 19:34
  • @13ruce Great! Answer written. – DavidPostill Jul 26 '17 at 19:53
1

In the loop, it returns the same value for the folder name each iteration of the loop

SET dirname=%filename:~0,13%

You need to use delayed expansion just like you did for number:

SET dirname=!filename:~0,13!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.