I am trying to create a batch-file to organize files by filetypes.
The idea is to move all files with extensions, except for the running script, into new directories, each named with the extension.
What code should I need to add or substitute for some of the code given below? This .bat file is in Documents folder and there are some files there.
#echo off
set x="%cd%\log.txt"
rem 'log.txt' contains the name of folder 'My Folder' and is already created in Downloads folder.
for %%a in (".\*") do (
for /F "tokens=*" %%i In ('type %x%') do (
if "%%~xa" neq "" if "%%~dpnxa" neq "%~dpnx0" (
if not exist "C:\Users\%username%\Downloads\%%i\%%~xa" md "C:\Users\%username%\Downloads\%%i\%%~xa"
move "%%a" "C:\Users\%username%\Downloads\%%i\%%~xa\"
)
)
)
pause
OUTPUT:
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
Press any key to continue . . .
This will create folders as C:\users\username\Downloads\.ext including the dot.
#echo off
set "x=%~dp0\log.txt"
rem 'log.txt' contains the name of folder 'My Folder' and is already created in Downloads folder.
for /F "delims=" %%i In ('type %x%') do (
if "%%~xi" neq "" if "%%~fi" neq "%~f0" (
md "%userprofile%\%%~xi" >nul 2>&1
move "%%~fi" "%userprofile%\Downloads\%%~xi\"
)
)
pause
If you do not want the dot. i.e C:\users\username\Downloads\ext
#echo off
setlocal enabledelayedexpansion
set "x=%~dp0\log.txt"
rem 'log.txt' contains the name of folder 'My Folder' and is already created in Downloads folder.
for /F "delims=" %%i In ('type %x%') do (
if "%%~xi" neq "" if "%%~fi" neq "%~f0" (
set "ext=%%~xi"
call set ext=!ext:.=!
md "%userprofile%\!ext!" >nul 2>&1
echo move "%%~fi" "%userprofile%\Downloads\!ext!"
)
)
pause
Note, I removed the %%i from the md command as it will create a folder with the name of the file, if that is what you wanted, just put it back.
Given my understanding of what you're trying to do, I would suggest something a little more like this:
#Echo Off
Set "DestDirName=My Folder"
If Exist "%~dp0log.txt" Set /P "DestDirName="<"%~dp0log.txt"
If Exist "log.txt" Set /P "DestDirName="<"log.txt"
For %%A In (*)Do If /I Not "%%A"=="%~nx0" If Not "%%A"=="log.txt" If Not "%%~xA"=="" (
Set "FileExtension=%%~xA"
SetLocal EnableDelayedExpansion
RoboCopy . "%UserProfile%\Downloads\%DestDirName%\!FileExtension:~1!" "%%A" /Mov>Nul
EndLocal
)
Pause
Lines 2, 3 and 4 will Set the name of the parent directory in Downloads which will hold the directories for your files to be moved to. I have used a new directory named My Folder as a backup just in case the file log.txt cannot be found in either the current directory, or that holding your running batch file. It currently selects the name in the following order of preference: 'current directory', 'batch file directory', 'My Folder'; you can switch lines 3 and 4, if you'd prefer the 'batch file directory' to take precedence over the 'current' directory. If log.txt is found, the Set /P command will set the variable DestDirName to the content of the first line of that file, please don't use doublequotes or a trailing backslash in that content.
The For loop will then proceed to move all files with extensions to directories named using their extension, without its leading period, held within the directory, from lines 2-4, and inside the users Downloads directory. When doing that it will not include itself or any file named log.txt.
BTW, it doesn't matter if the directory name string value of %DestDirName% already exists in Downloads, it will be created automatically if it doesn't.
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 new to batch Scripting. The requirement is, Directory contains folders with sub folders and files. Need to delete all files except two files, which contains the extension like .css .html. Don't know about batch(.bat) Scripting. Please help me
Thanks in Advance
you could try something like this which will loop through all directories from where the batch file is placed and delete files that don't match the desired extension
#echo off
echo.
REM loop through files
for /r %%f in (*) do call :myFunc %%f
goto End
REM function to check files
:myFunc
set file=%1
set delete=TRUE
REM don't delete the batch script (replace with your batch script name)
if not "%file%"=="%file:batchscriptname.bat=%" set delete=FALSE
REM don't delete .html files
if not "%file%"=="%file:.html=%" set delete=FALSE
REM don't delete .css files
if not "%file%"=="%file:.css=%" set delete=FALSE
REM execute the delete
if "%delete%"=="TRUE" echo %file%
goto :eof
:End
#Echo off
for / "delims=" %%A in (
'dir /B/S/A-d X:\startfolder\* ^|findstr /i /v "\.css$ \.html$" '
) Do echo Del "%%~fA"
If the output looks right, remove the echo in front of del.
I'm trying to get the full filename of the files in a directory that starts with for example SVR_OUTPUT_ just to validate if the file exists in the directory using batch script.
I was successful to get the file name in the directory to compare the names using:
#echo off
setlocal disableDelayedExpansion
:: Load the file path "array"
for /f "tokens=1* delims=:" %%A in ('dir /s /b^|findstr /n "^"') do (
set "file.%%A=%%B"
set "file.count=%%A"
)
:: Access the values
setlocal enableDelayedExpansion
for /l %%N in (1 1 %file.count%) do echo !file.%%N!
But I need to compare and check if the file names starts with SVR_OUTPUT_. I'm new to batch programming.
Could any one help me with this?
As written already by wOxxOm, all you need for listing all files from all subdirectories starting with SVR_OUTPUT_ is:
dir /S /B SVR_OUTPUT_*
Remove /S to get listed just the files in current directory not including subdirectories or a message that no file matching the pattern could be found.
The following code could be used to check if in current directory there is at least 1 file starting with SVR_OUTPUT_:
#echo off
if exist SVR_OUTPUT_* (
echo There are follwing files starting with SVR_OUTPUT_ in %CD%
echo.
dir /B /ON SVR_OUTPUT_*
) else (
echo There is no file starting with SVR_OUTPUT_ in %CD%
)
pause
I need a batch script,
I am writing a batch script for renaming a folder to a number and that number should not be the same.. Every time I click the batch file, it should be a random number.
eg:
folder name is "temp"
If I run the bat file that folder name should be change to a random number.
eg:
1st time : folder name after rename can be "34324"<br/>
2nd time : folder name after rename can be "29389"<br/>
.
.
.
.
.
nth time : folder name after rename can be "xxxxx"
please teach me how to do this..
I am a newbie in this field..
This batch file saves the information about the last folder name inside itself. Each time it is run, it retrieves this information. If not found, temp is assumed. If folder does not exist, it is created. If it exists, a new name is searched, the folder is renamed and the information saved inside batch file.
#echo off
setlocal enableextensions disabledelayedexpansion
rem Determine where to work
if "%cd:~-1%"=="\" ( set "where=%cd%" ) else ( set "where=%cd%\" )
rem Determine what to search for in the current file
set "testString=:::set lastName=[0-9][0-9]*"
rem Retrieve the last name used
set "lastName="
for /f "tokens=* delims=:" %%a in ('findstr /r /b /e /c:"%testString%" "%~f0"') do %%a
if not defined lastName set "lastName=temp"
rem If the last folder does not exist, create it and finish
if not exist "%where%%lastName%\" (
mkdir "%where%\%lastName%"
echo(Folder [%lastName%] has been created
goto endProcess
)
rem Search for a new name
;:newNameLoop
set "newName=%random%"
if "%newName%"=="%lastName%" goto newNameLoop
if exist "%where%%newName%" goto newNameLoop
rem Rename the folder to the new name
ren "%where%%lastName%" "%newName%" 2>nul && set "save=1" || set "save="
rem If there were no problems, save the new name in current batch file
if defined save (
for /f "tokens=1,* delims=:" %%a in ('findstr /n /r /b /e /v /c:"%testString%" "%~f0" ^& break ^> "%~f0"') do >>"%~f0" echo(%%b
>>"%~f0" echo(:::set lastName=%newName%
echo Renamed [%lastName%] into [%newName%]
) else (
echo Rename operation failed. Ensure folder is not in use
)
rem End of the process, clean and exit
;:endProcess
endlocal
exit /b
And no, the added semicolon in labels is not a typo error. They (or other character) are needed to avoid problems with the delims=:
I have made this for you:
#echo off
:retry
SET /A test=%RANDOM% * 10000 / 100000 + 1
echo %test%
IF EXIST %~dp0\%test% GOTO retry
md "%~dp0\%test%"
GOTO retry
It's quite quick 100+ folders per second, so watch out.
I am looking for a simple batch or vbs script I can edit to complete the following tasks.
Search a folder (including sub dirs) for *.rar files.
Extract the *.rar found to a specific drive i.e E:/ or F:/ (I can change the file for this)
The twist, is the script must rename the extracted file to the directory name.
i.e
C:\Documents\Shop1_A\file.rar
Inside file.rar there is a file.pdf
I require the script to extracted the file.rar to a drive and rename the extracted file to E:\Shop1_A.pdf
There will only ever be 1 file in the archive (no duplicate or overwrite errors)
set "sourceDir=c:\someware"
set "targetDir=f:\"
set "unrar=c:\program files\WinRar\unrar.exe"
for /r "%sourceDir%" %%f in (*.rar) do for /d %%d in ("%~dpf\.") do (
"%unrar%" p -inul "%%~f" > "%targetDir%\%%~nd.pdf"
)
do you only have pdf files? If not, try this:
#ECHO OFF &SETLOCAL
set "SourceFolder=%userprofile%"
set "DestinationFolder=%temp%"
for /d /r "%SourceFolder%" %%a in (*) do for %%b in ("%%~fa\*.rar") do for /f "delims=" %%c in ('rar lb "%%~Fb"') do (
rar e -idq "%%~fb" "%%~c" "%DestinationFolder%"
ren "%DestinationFolder%\%%~c" "%%~na%%~Xc"
)
If you don't own rar, you can also work with the free unrar.