Friday, August 11, 2017

command line - Batch to Create a Subdirectory for Each file in Main Directory


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
)

Answer



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!



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...