hope you can help me with this, i can't make it work what i need
I need to copy all the .pdf files from a source folder, create a folder with part of the name "T-123456" and add the respective PDF files found in the correct folder in the destination folder, but sometimes the name it varies or the reference change "SM17-123".
Example of files
HC002T-1234562436787004332
MV002T-1234562436787004332
PP _002_T-123456_24_3678_7004332
Types of direfents files
HC123CLG-32-172436787004259
HC123SM17-1802436787004044
i have this code created but it makes part of the job because the name varies and create folders incorrect for that files, sometimes the files have more digits in the beggining example 001 or 0001, so i dont know how to omit the other references files and only work whith files "T-123456" also i need the batch continuously working for new files created in the source folder and if i have another routhe where i have other types of file and copy to the correct reference it would be great.
#echo off
title Electronic File
:loop
cls
timeout -t 1 >nul
color b
for %%A in (*.pdf) do (
echo File Found %%A
for /f "delims=" %%B in ("%%A") do set fname=%%~nB
for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
for /f "tokens=1* delims=" %%D in ("!fname:~5,8!") do set folname=%%D
echo Name folder !folname!
if not exist "!folname!" (
echo Folder !folname! dont exist, creating
md "!folname!" 2>nul
) else (
echo Folder !folname! exists
)
echo Copying file %%A to folder !folname!
xcopy "%%A" "!folname!"
)
echo on
md "C:\test %All%"
xcopy /s /y "X:\test\pdf" "W:\Electronic File %All%"
goto :loop
pause
for %%A in (*.pdf) do (
echo File Found %%A
set fname=%%~nA
set fextn=%%~xA
set folname=!fname:~5,8!
ECHO !folname!|FINDSTR /i /r "[A-Z]-[0-9][0-9][0-9][0-9][0-9][0-9]" >NUL
IF ERRORLEVEL 1 (
ECHO %%A - !folname! excluded
) ELSE (
echo Name folder !folname!
if not exist "!folname!" (
echo Folder !folname! dont exist, creating
ECHO md "!folname!" 2>nul
) else (
echo Folder !folname! exists
)
echo Copying file %%A to folder !folname!
ECHO xcopy "%%A" "!folname!"
)
)
Here's the meat of the matter. delayedexpansion needs to be on - you don't show that in your original code.
Note that there is no requirement for %%B, %%C, %%D as within the loop, %%A contains the filename and hence you can set the variables from that name.
Note that fextn will apparently always be .pdf since that is the extension you specify in your filemask *.pdf so setting it seems superfluous.
The syntax SET "var=value" (where value may be empty) may be used to ensure that any stray trailing spaces are NOT included in the value assigned.
The change I've introduced is to echo the directoryname to findstr, searching /i case-insensitively for /r a regular-expression which is one letter, a dash and then 6 numerics. If the directoryname matches then errorlevel will be set to 0 by findstr, otherwise, it will be set to 1.
The if errorlevel 1 means "if errorlevel is 1 or greater" and if that is so, the match was UNsuccessful, so report the filename and extracted directoryname; otherwise, go through your logic (I've changed it to simply echo the md and xcopy commands, for testing).
Given that we now have a variable structure,
for %%A in (*.pdf) do (
echo File Found %%A
set "copied="
set fname=%%~nA
set fextn=%%~xA
set folname=!fname:~5,8!
ECHO !folname!|FINDSTR /i /r "[A-Z]-[0-9][0-9][0-9][0-9][0-9][0-9]" >NUL
IF not ERRORLEVEL 1 call :process "%%A"
rem repeat this section for each match required - begin
if not defined copied (
set folname=!fname:~5,9!
ECHO !folname!|FINDSTR /i /r "[A-Z][A-Z][A-Z]-[0-9][0-9]-[0-9][0-9]" >NUL
IF not ERRORLEVEL 1 call :process "%%A"
)
rem repeat this section for each match required - end
if not defined copied ECHO %%A - !folname! excluded
)
goto :eof
:process
echo Name folder %folname%
if not exist "%folname%" (
echo Folder %folname% dont exist, creating
ECHO md "%folname%" 2>nul
) else (
echo Folder %folname% exists
)
echo Copying file %~1 to folder %folname%
ECHO xcopy "%~1" "%folname%"
set "copied=Y"
goto :eof
In your extended examples, it's not clear where the PP fits into the scheme.
The formula is reasonably simple. The start position is the first argument in the set (counting from first character=0) and the second the length to select. The regex match may be either a single character (matched literally) or [rangestart-rangeend] . matches any one character, so the first block I've shown selects from HC123CLG-32-172436787004259 from the 5th character (starting at 0) for 9 characters =CLG-32-17 and matches this against alpha,alpha,alpha,-,numeric,numeric,-,numeric,numeric.
On a match, errorlevel is set to 0, so the :process subroutine is called, with a parameter of %%A in quotes. The subroutine uses the value in folname and copies the file (name now in %1 - %~1 removes the quotes) as before.
So - it's as simple as repeating the block of code, altering the start and length of the string to be selected and changing the regex to suit the required pattern.
Related
I'm trying to create a batch file script that will compress all subfolders named folder1 within a directory, BUT it should only compress this folder if it does NOT contain another subfolder with the same name.
I am very new to cmd and batch files, and this is also my first post of stack overflow, please let me know if I've failed to give some information that I should!
The bit of pseudo-ish code below hopefully illustrates what I'm trying to accomplish:
#echo off
SETLOCAL EnableDelayedExpansion
FOR /D /R %%G IN (*folder1*) DO (
CD %%G
SET /A compress=true
FOR /D /R %%H IN (*folder1*) DO (
ECHO folder contains another folder of same name, should not be compressed
SET /A compress=false
)
IF !compress!==true (
ECHO Run compression operation on folder
"C:\Program Files (x86)\7-zip\7z.exe" a -tzip "%%G.zip" "%%G\"
)
)
Please ask away if anything seems unclear! I'm really hoping to turn the above into functional code, thank you in advance for any input or thoughts.
#ECHO OFF
SETLOCAL
:: Starting directory
SET "sourcedir=U:\sourcedir"
:: name of directory to compress
SET "targetname=targetdir"
FOR /d /r "%sourcedir%" %%a IN (*) DO (
IF /i "%%~nxa" == "%targetname%" IF NOT EXIST "%%a\%targetname%\." (
ECHO compress %%a
rem temporarily switch to target directory
PUSHD "%%a"
ECHO 7z a -tzip "%%a.zip"
rem back to original directory
POPD
)
)
GOTO :EOF
This should do as you want - it will echo not execute the 7z command.
The if sees whether the "name and extension" portion of the directory-name in %%a matches the target (the /i makes the match case-insensitive). If it matches AND there is a subdirectory with the required name, then the compression portion is executed.
There are two points to consider.
First, the name of the destination ZIP file. As you have written it, the ZIP generated would be folder1.zip in the parent directory. IDK what you want here. This code would do the same, but %%a.zip could be replaced by ..\%targetname%.zip since the pushd/popd changes the current directory to the folder1 directory and .. means the parent directory.
The second matter is whether or not you want to compress ...\folder1\folder1 (which would have a destination ZIP file of ...\folder1\folder1.zip)
Revision given comment:
#ECHO OFF
SETLOCAL
:: Starting directory
SET "sourcedir=U:\sourcedir"
:: name of directory to compress
SET "targetname=targetdir"
REM (
FOR /d /r "%sourcedir%" %%a IN (*) DO IF /i "%%~nxa" NEQ "%targetname%" (
rem calculate parent name in %%~nxp and grandparent in %%~nxg
FOR %%p IN ("%%~dpa.") DO FOR %%g IN ("%%~dpp.") DO (
IF /i "%%~nxp" == "%targetname%" IF /i "%%~nxg" NEQ "%targetname%" (
ECHO child %%~nxa
ECHO parent %%~nxp
ECHO Gparent %%~nxg Gppath=%%~dpg
ECHO compress %%a
rem temporarily switch to target directory
PUSHD "%%a"
ECHO 7z a -tzip "%%a.zip"
ECHO -------------------
rem back to original directory
POPD
)
)
)
GOTO :EOF
It's not that clear what you want to do with a directory named ...\folder1\folder1\something or what the target ZIP file-name should be.
The if in the for /d /r line will ensure that only leaf-names that do not match the target name are processed. The path-name in %%a is then processed into the parent and grandparent portions - note that %%~dp? is the drive+path portion of %%? which terminates \ so appending . to this resolves to effectively removing the terminal \ yielding a "filename".
You appear to want to compress directories that have a parent but not a grandparent named with the target string, hence the innermost if statement.
I've just echoed the various strings available at this point so they may be strung together as required to form your destination ZIP file-name. Note that the pushd/popd bracket ensures that the current directory at the time of the compress is the leaf to be compressed.
I am in the middle of batch extracting screenshots for contents we are planning to use on a tube site I am working on.
The jpeg files per content is labled as followed:
6c82c0239f6eb839-1
6c82c0239f6eb839-2
all the way to 120
The file name is different per content
a82384e2c46ba4af-1
a82384e2c46ba4af-2
etc.
They will all be extracted to a singe folder.
So I basically need a batch file that will create folders based on the content name without the dash and number and move all 120 jpegs in the folder with the content name.
For example:
Create folder named 6c82c0239f6eb839 and
move 6c82c0239f6eb839-1 to 6c82c0239f6eb839-120 in to the created folder.
I saw another thread with the following batch file. its pretty much what I want but the folder name is only 3 characters long and the files are copied to the newly created folders instead of moving them.
#echo off
SetLocal EnableDelayedExpansion
for /F "delims=" %%a in ('dir /b *.jpeg') do (
set Name=%%a
set Folder=!Name:~0,3!
xcopy /y "%%a" !Folder!\
)
Could someone change this so that it will display full file name without the dash and number for the folders and move files in its respective folders instead of copy?
Thank you
#echo off
setlocal
#rem Get each jpeg file.
for /F "delims=" %%A in ('2^>nul dir /b *.jpeg') do (
rem Get filename as token before the dash.
for /f "delims=-" %%B in ("%%~A") do (
rem Make dir if needed.
if not exist "%%~B" md "%%~B"
rem Check if isdir.
2>nul pushd "%%~B" && popd
if errorlevel 1 (
>&2 echo Failed isdir "%%~B".
) else (
rem Do the move operation.
>nul move /y "%%~A" "%%~B"
if errorlevel 1 (
>&2 echo Failed move "%%~A" to "%%~B"
)
)
)
)
exit /b %errorlevel%
The code is well remarked so if you want to understand
the evaluated code by changing #echo off to #echo on.
The use of %errorlevel% after the exit /b is not
required though will let you know what the errorlevel is
when #echo on is used.
The pushd tests for a directory
(even if it is a symlink).
errorlevel is checked to decide if to echo a
error message or do the move.
As the for loop variables are used direct, use of
enabledelayedexpansion is not needed.
Many commands support the argument of /? to get help
about the command. i.e. move /?.
If you only try to copy the correct jpeg to the correct folder, you can do this:
#echo off
SetLocal EnableDelayedExpansion
CD <CORRECT ROOT PATH>
for /F "delims=" %%a in ('dir /b *.jpeg') do (
set Name=%%a
REM I presume all the files have 16 characters before the dash
set Folder=!Name:~0,16!
IF NOT EXIST !Folder! MKDIR !FOLDER!
xcopy /y "%%a" !Folder!\
)
I was not able to test.
First of all, I would like to apologize for my manners regarding my initial post.
The answer by micheal_heath has resolved my issue.
Furthermore, I happened to find this post by user Salmon Trout from a different site which also worked.
Batch file to make folders with part of file name and then copy files
#echo off
setlocal enabledelayedexpansion
for %%A in (*.psd *.jpg) do (
echo file found %%A
for /f "delims=" %%B in ("%%A") do set fname=%%~nB
for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
for /f "tokens=1* delims=_" %%D in ("!fname!") do set folname=%%D
echo folder name !folname!
if not exist "!folname!" (
echo Folder !folname! does not exist, creating
md "!folname!"
) else (
echo Folder !folname! exists
)
echo Moving file %%A to folder !folname!
move "%%A" "!folname!"
)
echo Finished
pause
I just changed the the following line remove the hypen and numbers to create folders for the file name properly.
for /f "tokens=1* delims=-***" %%D in ("!fname!") do set folname=%%D
I still lack the knowledge on why and how both methods work, but this has been an interesting start for me. I hope other beginners trying to solve a similar issue can find something useful from this post.
Under the path U:\test\0014* I have 99 folders and each of them has respectively 2 subfolders MASTER and DERIVATIVE_COPY. With a following script I try to count the number of PDFs in MASTER folder. If there are only one .pdf file there I want to copy it to DERIVATIVE_COPY folder. IF there are 0 or >1 .pdf in MASTER I want only to show the number of them. This operation should be done for each of the 99 folders.
#echo off
setlocal enabledelayedexpansion
for /R U:\test\0014\*\MASTER %%i in (*.pdf) do (
set /a anzahl+=1
)
if !anzahl! EQU 1 ( echo !anzahl! )
if NOT !anzahl! EQU 1 ( echo !anzahl! )
pause
#ECHO OFF
SETLOCAL enabledelayedexpansion
SET "sourcedir=U:\sourcedir"
for /f %%i in ('dir /ad /s/b "%sourcedir%\master*"') do IF /i "%%~nxi"=="MASTER" (
SET /a found=0
FOR %%x IN ("%%i\*.pdf") DO SET /a found+=1
IF !found!==1 (
XCOPY /y "%%i\*.pdf" "%%i\..\derivative_copy\" >nul
) ELSE (
ECHO !found! .pdf files found IN "%%i"
)
)
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
First, execute a dir to get a directory-list of the "files" names that start master in the specified tree. Use /ad to select only the directory-names. Accept only those names where the "name+extension" is master (disregarding case)
For each directory-name found, set found to 0 then increment found for each .pdf file found in the directory %%i.
If the resultant count in found is 1, xcopy the file found to the destination subdirectory (which conveniently creates the subdirectory if it doesn't already exist), using /y to overwrite any existing file of the same name and >nul to make the process silent.
Otherwise, report the directoryname and count of files.
I'm working on a script for copying files in a folder which corresponds to the file's name and I have that part worked out using a FOR loop which checks to make sure the destination folder exists and copies the files once it has verified that it does. Example: 11-01111_ABC_DEF.pdf would go into /11/0111/. The length may vary by one or two characters but the format is consistent. I've copied my basic script below.
My problem is that sometimes a file with the same name needs to be processed. How could I go about concatenating a number to the end of the file if one or more copies of the file already exists in the destination folder?
setlocal enableextensions enabledelayedexpansion
for %%x in (*.PDF *.TXT) do (
set "source="C:\files"
set "dest=R:\"
set "filename=%%x"
set "prefix=!filename:~0,2!"
set "folder=!filename:~3,5!"
if not exist !dest!\!prefix!\!folder! MOVE !filename! !source!\failed
if exist !source!\!filename! MOVE !filename! !dest!\!prefix!\!folder!
)
setlocal ENABLEDELAYEDEXPANSION
set "dest=worked"
for %%i in (*.pdf *.txt) do (
for /f "tokens=1-3* delims=-_." %%j in ("%%i") do (
if exist "%dest%\%%j\%%k" if exist "%dest%\%%j\%%k\%%i" if exist "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" (
for /f "tokens=1-9* delims=-_." %%n in ('dir %dest%\%%j\%%k\%%j-%%k*-* /b') do set /a inc=%%p
set /a inc+=1
move "%%i" "%dest%\%%j\%%k\%%j-%%k-!inc!_%%l_%%m" || move "%%~i" "failed"
set inc=
)
if exist "%dest%\%%j\%%k\%%i" if not exist "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" (
move "%%i" "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" || move "%%~i" "failed"
)
if exist "%dest%\%%j\%%k" if not exist "%dest%\%%j\%%k\%%~i" (
move "%%~i" "%dest%\%%j\%%k\%%~i" || move "%%~i" "failed"
)
if not exist "%dest%\%%j\%%k" move "%%~i" "failed"
)
)
put this in the folder with the .txts and .pdfs comment if you want me to change something.
I have several folders that have files with double file extensions along with regular file extensions. I need to create a batch script to search all the folders and remove the last extension with any files that have double extensions. None of the file extensions are consistent.
Here's an example
C:\test\regular.exe
C:\test\picture.jpg.doc
C:\newtest\document.doc.pdf
End Result I need
C:\test\regular.exe
C:\test\picture.jpg
C:\newtest\document.doc
#ECHO OFF
SETLOCAL
SET sourcedir=c:\sourcedir
FOR /r "%sourcedir%" %%i IN (*.*) DO (
FOR %%n IN ("%%~ni") DO IF NOT "%%~xn"=="" IF NOT EXIST "%%~dpni" ECHO REN "%%~fi" "%%~ni"
FOR %%n IN ("%%~ni") DO IF NOT "%%~xn"=="" IF EXIST "%%~dpni" ECHO CAN NOT REN "%%~fi" "%%~ni"
)
GOTO :EOF
This batch should accomplish the task.
For each file in the tree rooted at sourcedir, if the NAME of the file itself contains an 'extension' and the filename without the original extension does not exist, then rename the file. That way, if ...picture.jpg.doc is found, the rename should occur only if ...picture.jpg does not exist.
The command to rename is simply ECHOed. You'd need to remove the ECHO keyword to activate the rename - after verifying that's what you want to do.
I've added a second line to report that a rename could not be done because of an existing file.. This could be done very slightly better, but it will work.
Revised to modify name in case simple rename can not be done.
Caution - this version will rename immediately - there are no ECHOes to provide a list first because it's nonsense to provide such a list when renaming a file may produce different results on the main rename run.
#ECHO OFF
SETLOCAL
SET sourcedir=c:\sourcedir
FOR /r "%sourcedir%" %%i IN (*.*) DO (
FOR %%n IN ("%%~ni") DO IF NOT "%%~xn"=="" IF EXIST "%%~dpni" (
SET renreq=Y
FOR %%a IN (new alt extra another 1 2 3 4 5 6 7 8 9) DO IF DEFINED renreq (
IF NOT EXIST "%%~dpi%%~nn_%%a%%~xn" (
REN "%%~fi" "%%~nn_%%a%%~xn"
SET "renreq="
)
)
IF DEFINED renreq ECHO CAN NOT REN "%%~fi"
) ELSE (
REN "%%~fi" "%%~ni"
)
)
GOTO :EOF
Reasonably obviously, the list of "extras" can be extended if required.
Try this and remove the echo, if the output is OK:
#echo off &setlocal
for /r \ %%i in (*) do (
for %%j in ("%%~ni") do if "%%~xj" neq "" echo ren "%%~fi" "%%~nj"
)
Edit: added support for the entire HD.