Batch create folders from files with similar beginning but different ending - batch-file

I have a lof of files with similar beginning names, but ending different. I have to create a folder for every "series" of files, which means all files whose names begin with the same 7 characers.
See image for visualization:
The code I have right now is
for /F "Tokens=*" %%i in ('Dir /B *.jpg') do md "%%~ni"|copy "%%i" "%%~ni"
Which just creates a folder for every file and puts it inside.
Unfortunately I don't have enough knowledge of this language and just googling it only made me learn how to create a substring SET _result=%_test:~0,7% but not how to create folders with that.
I'm sure it's just a short sequence, could someone help me with that?

This may not be the most efficient way of doing this, but it should help you. The below batch script takes an input folder and output folder as inputs from user. It then iterates through all the files in the input folder and copies them to output folder under a sub-folder with first 7 characters of the filename.
#echo OFF
setlocal ENABLEDELAYEDEXPANSION
REM Get input directory from user
set /p INPUT_DIR=Please enter full path to directory with files:
REM Get ouput directory from user
set /p OUTPUT_DIR=Please enter full path to output directory:
REM Iterate through files and create necessary folders/copy files
for /f %%f in ('dir /b %INPUT_DIR%') do (
set fullname=%%f
set trimmedname=!fullname:~0,7!
set fullpath=%OUTPUT_DIR%\!trimmedname!
if not exist !fullpath! md !fullpath!
copy %INPUT_DIR%\%%f !fullpath!
)
Here's a sample output that shows the processing done by the script:

Related

In Batch, how to copy files within a user specified range

I have a scenario where I need to copy files from five subdirectories to the directory where the batch file exists. These files are sequential in name in each subdirectory. For example:
FolderA:
A001.txt
A002.txt
A003.txt
A004.txt
FolderB
B001.txt
B002.txt
B003.txt
B004.txt
FolderC
C001.txt
C002.txt
C003.txt
C004.txt
and so on. What I want to be able to do is have a user input where I am able to copy the files from each directory that end in 003 and 004 to a new directory. I have more of the batch that does some data scrubbing from there with the copied files. My problem is getting the files copied based on my number range.
I am able to add a user input to allow me to select all file that end in 003 and copy them, but then I have to run it again to get all files that end in 004. I have close to 25,000 files to search through, and I have completed data mining some. I need to copy them in from a range.
Here is what I have that works to allow me to input and copy a single file set
set fname=
set /P "FileNumber=Please enter File Number: "
if defined FileNumber for /R "\client\A001\M0093" %%I in ("*%FileNumber%*.xml") do (copy /Y "%%I" "\Extraction\Files\"
set "fname=%%~I"
)
if defined fname (
cls
#echo off
copy "Files\*.txt" Data.txt
Any help would be greatly appreciated.
I am posting from my mobile, so none of this has been tested:
#echo off
set /P "begin=beginning number"
set /P "end=Ending number"
Pushd "client\A001\M0093"
For /l %%i in (%begin%,1,%end%) do for /R %%b in ("*%%i*.xml") do copy /Y "%%~b" "%~dp0"
Also, this assumes the files are copied to the path where the batch-file is located, as you have mentioned.

How can I improve a batch file with a conditional who copy a jpg file refferring to a specific extension and to a specific database?

I created a .bat file with the following code in order to copy a random file from a directory A-POOL FOLDER into a directory B-FOLDER (with a fixed file name video.mp4). So, in the directory A there is a pool of .mp4 file, and in the directory B there is the the file video.mp4 (same name, but different video every time I execute my batch-file).
That's a code who do this. It perfectly works.
#echo off
setlocal EnableDelayedExpansion
cd C:\Users\aless\Desktop\example\A-POOL
set n=0
for %%f in (*.*) do (
set /A n+=1
set "file[!n!]=%%f"
)
for /L %%i in (1,1,%time:~-1%) do set "dummy=!random!"
set /A "rand=(n*%random%)/32768+1"
copy "!file[%rand%]!" C:\Users\aless\Desktop\example\B-FOLDER\video.mp4
FOR %%G IN ("!file[%rand%]!") DO >"C:\Users\aless\Desktop\example\B-FOLDER\title.txt" ECHO %%~nG
Now the question (different from last time):
In the directory A-POOL I have a lot of .mp4 files. I changed manually the .mp4 extension of every file with a code who rappresent a food.
For example: Filename.pizza, Filename2.pizza, Filename.pasta, Filename200.pasta, Filename.cheeseburger etc...
I created another folder named "FOOD-DATABASE" (in C:\Users\aless\Desktop\FOOD-DATABASE) who contains a big database of images in .jpg extension of the foods. The file NAMES of the food database are equal to the file EXTENSIONS of the files contained in A-POOL folder
Content of FOOD DATABASE folder:
(pasta.jpg, pizza,jpg, cheeseburger.jpg... etc..).
So I need to add to the code a string/conditional who execute e command who say:
If the picked random File have the extension .pizza COPY pizza.jpg from C:\Users\aless\Desktop\FOOD-DATABASE into C:\Users\aless\Desktop\B-FOLDER\FOOD.JPG (fixed name file)
Actually I don't want to add this strings for every food type... in few word the code strings have to read the extension of the picked random file and copy from C:\Users\aless\Desktop\FOOD-DATABASE to C:\Users\aless\Desktop...B FOLDER\FOOD.JPG (fixed name file) the file with the same name to the extension of the random file.
It's a mess... I know ;) Thanks for your help!
As mentioned in the comments, we know that the extension of the one file is the name of another file. so these variable expansions are important:
%%~nG
%%~xG
The last for loop sets a variable %food% from expanded %%~xG which is the extension of the file and using a random example would be .pizza We just need to get rid of the . and you have pizza. We do this by %food:~1.
#echo off
setlocal EnableDelayedExpansion
pushd "%userprofile%\Desktop\example\A-POOL"
set n=0
for %%f in (*.*) do (
set /A n+=1
set "file[!n!]=%%f"
)
for /L %%i in (1,1,%time:~-1%) do set "dummy=!random!"
set /A "rand=(n*%random%)/32768+1"
copy "!file[%rand%]!" "..\B-FOLDER\video.mp4" /Y
for %%G IN ("!file[%rand%]!") DO (
echo %%~nG > "..\B-FOLDER\title.txt"
set "food=%%~xG"
)
copy "..\FOOD-DATABASE\%food:~1%.jpg" "..\B-FOLDER\food.jpg" /Y
popd
Notes!
I am using pushd instead of cd and using relative path, not full paths as we are working in the same folder structure.
I can make out that you are running this on your own profile, so I replaced C:\users\<username> with %userprofile% in the event someone else wants to run it from a similar folder, their <username> will be different.
popd at the bottom of the script simply changes back to the previous working directory you were in before the last pushd. it is not needed for this particular script, but adding it so you can learn about it compared to pushd
All of the items I modified has some good help topics, you can find help topics on cmd by simply running the command name with an appended /? for instance for /?, set /? etc.

How to write a Batch Script that searches for files based on list

Can anyone assist me in writing a batch script that searches for file names and outputs the location of the files to a text file. Example I have a file called list.txt located in a folder, C:\LocateFiles\list.txt. Located in the list.txt file are about 25 file names that I wish to determine if they are anywhere on the C:\ drive. If it locates any of the file names identified in the file list.txt it will output the path of all files found to a single file in C:\LocatedFiles\results.txt.
A million thanks,
Johnny Mac
#ECHO OFF
FOR /F %%F IN (C:\LocateFiles\List.txt) DO DIR /s/p/b %%F.* >> C:\LocateFiles\finds.txt
Save that as LocateFiles.cmd and place it in whichever directory you wish to search, note that C:\ is very large and will take quite a while! as in, forever, seriously, i really wouldnt, your call...
the file finds.txt will have the entire path for any file that matches up to the file names listed in List.txt
Also note, this finds files of any extension, but the filename itself must match exactly to whats in List.txt
The solution below search the files in the current directory just once, so it run faster.
#echo off
dir /S /B /A-D | findstr /I /G:C:\LocateFiles\list.txt > C:\LocatedFiles\results.txt
EDIT: New method added
The method below may run even faster. It is necessary to complete a timing test.
#echo off
setlocal EnableDelayedExpansion
rem Read file names from file list and assemble a long string with this format:
rem "filename1.ext*" "filename2.ext*" ...
set "fileList="
for /F "delims=" %%a in (C:\LocateFiles\list.txt) do set fileList=!fileList! "%%a*"
rem Search the files from current directory downwards
(for /R %%a in (%fileList%) do echo %%a) > C:\LocatedFiles\results.txt

ROBOCOPY - Copy folders content to a single folder WITH file list

Since I cannot add a comment, I am asking a related question.
The original posting found here works quite well.
Is there a way to use this with a list of file names? I've seen where a file list can be passed to the ROBOCOPY command but I have been unable to get it to work.
Taking a step back, I have a series of folders and there are specific files inside of them that I want to copy out to a single folder. I have a text file which lists the names of these files.
I am looking for a batch routine that will look for each of the files in the text file in each of the folders and then copy the files out to a new folder.
Thank you!
Test this - the file.txt has a filename on each line.
It doesn't handle filename conflicts.
#echo off
cd /d "c:\base\folder"
for /f "usebackq delims=" %%a in ("file.txt") do (
for /f "delims=" %%b in ('dir "%%a" /b /s /a-d ') do copy "%%b" "d:\target\folder"
)
I recently had to tackle this problem, and many files that I wanted to move to from the hierarchy to a single folder had the same name as each other, and I wanted to still flatten the hierarchy without them to being over-written.
What I did was write a script that moves the file, but renames it with the old hierarchy path in the name
for example:
source files:
C:\files\somefiles\file.txt
C:\files\otherfiles\file.txt
destination is C:\newdir\
files are created as
C:\newdir\somefiles-file.txt
C:\newdir\otherfiles-file.txt
here is the code, batch file 1 goes thru the files, batch file 2 renames and moves them (could also copy instead, if you want to preserve the source:
#echo off
for /r %%f in (*.*pr) do #renameandmovefilespart2.bat "%%f" "%%~ff" "%%~xf"
renameandmovefilespart2.bat
#echo off
Setlocal EnableDelayedExpansion
rem set the whole file path
set origWhole=%1
set origPathOnly=%2
set extension=%3
rem here you can set where the directory to hold the flattened hierarchy is
set destDir=c:\destinationDir\
rem set the directory to do a string replace
rem make this the starting directory, that you dont want in the newly renamed files
set startingDir=C:\starting\directory\
set nothing=
set slash=\
rem here you can set what the character to represent the directory indicator \ in the new files
set reaplcementDirectoryCharacter=--
set quote="
rem cut out the starting part of the directory
call set newname=%%origWhole:!startingDir!=!nothing!%%
rem replace slashes with new character
call set newname=%%newname:!slash!=!reaplcementDirectoryCharacter!%%
rem remove quotes
call set newname=%%newname:!quote!=!nothing!%%
rem #echo shortened: %newname%
rem #echo source path: %origPathOnly% newPath: %startingDir%
rem #echo extension: %extension%
rem rename the files
ren %origWhole% %newname%
rem prepare to move the file, clean up the source path
call set origPathOnly=%%origPathOnly:!quote!=!nothing!%%
move "%origPathOnly%%newname%" "%destDir%"

Batch read and rename from text file issue?

I'm a beginner with .bat files, and I'm attempting to rename multiple drawing (.dwg) files using a list generated in notepad. The notepad list contains a list of drawing numbers that look like this:
01013-13000p001
06301-12550p001
etc..
There is hundreds of them, and I want to take those numbers from the text and put it into a blank series of dwg files that are generic named for now (drawing.dwg, drawing(2).dwg, drawing(3).dwg etc..) I've only come up with a way to read a text file, but cant figure out how to take from the text file and rename multiple drawing files with it. Below is as far as I have gotten, after failed attempts of trying to take whats read from a text file and put it into the .dwg files. I plan on working this out in all the same directory, and any suggestions will be greatly appreciated. Thanks.
#echo off
for /f "tokens=* delims=" %%x in (dwgNumbers.txt.txt) do echo %%x
pause
would
for /f "delims=" %%x in (dwgNumbers.txt.txt) do echo copy /b "blank generic drawing.dwg" "%%x.dwg"
(as a batch line) do what you want? - note that the ECHO keyword is there to show what would be done. The echo keyword needs to be removed to actually execute the copy.
This will take the numbers from .txt, renaming the existing .dwg files with the data readed. If there are more files that numbers in .txt, it will rename until number exhaustion, no more.
for loop is using a dir command to get the list of files to avoid the case of files that after being renamed falls under the filter of the for and gets reprocessed.
This code has a echo command included in rename line to prevent data loss in case of malfunction. When the output to console is what is needed, remove the echo command from the rename line.
#echo off
rem Prepare environment
setlocal enableextensions enabledelayedexpansion
rem Read input file for numbers
< dwgNumbers.txt (
rem Process dwg files in directory
for /f "tokens=*" %%f in ('dir /b *.dwg') do (
rem Get number from input file
set "number="
set /p "number="
rem If there is a number, rename the file
if defined number echo ren "%%~f" "!number!.dwg"
)
)
rem Clean
endlocal

Resources