Append String to file name in dos Syntax Error Need - batch-file

#ECHO off
title Rename Script
set dir1=%1
set STR=%2
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
FOR %%n in (%dir1% *.*) DO (
ren %%n %STR%%%n
echo %STR%%%n)
echo done
pause
C:>yogesh>LDK.bat C:\yogesh app
OUTPUT:
Running Rename Script for STR=app
The syntax of the command is incorrect.
appC:\yogesh
appa3dapi.dll
appHLTV-Readme.txt
apphltv.cfg
appkver.kp
applanguage.inf
appLDR.bat
appMp3dec.asi
appMss32.dll
appMssv12.asi
appMssv29.asi
appTrackerNET.dll
The batch file cannot be found.
C:\yogesh>
There are few issues with this script:
" The syntax of the command is incorrect." I do not know where is the problem in script.
How to get the count of number of files renamed ?
Files get renamed into the directory where the .bat file resides I want to rename the files in specified folder as argument in variable dir1
Please let me know if you need more information.

Here is a solution without using CD. You needed to put a \ between your dir1 variable and *.* instead of a space. You needed quotes to protect against spaces in names. Use FOR variable modifiers ~nx to get just the name and extension (removes any drive and path info). Finally, use SET /A to perform math.
#ECHO off
title Rename Script
set "dir1=%~1"
set "STR=%~2"
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
set cnt=0
FOR %%F in ("%dir1%\*.*") DO (
ren "%%F" "%STR%%%~nxF"
echo %STR%%%~nxF
set /a cnt+=1
)
echo %cnt% files were renamed.
echo done
pause

Here you go:
#ECHO off
title Rename Script
set /A count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
set /p STR=choose a start-string:
echo Running Rename Script for STR=%STR%
FOR %%n in (*.*) DO (
ren "%%n" "%STR%%%n"
echo "%STR%%%n"
set /A count+=1)
echo count %count%
echo done
pause
we can save the current path in OLDDIR and then change the path to the one the user gave, at the end of the script we'll go back to OLDDIR using CD
you need to set the counter with /A
UPDATE for dbenham:
A small proof :)) that it worked (for me) with filenames that contains spaces:

Related

Backup a File or Folder when dropping it on the same bat

So I've managed to cobble together a script witch works as intended for files when using "copy". It creates a backup folder "_OLD" and makes an iterated (file001, file002, etc) copy of the file I dropped on my bat by checking for the highest version in the backup folder. How ever I would like to have only one bat that would work the same way for both a file or folder. By substituting "copy" with "xcopy" I managed to copy the folder but now the file wont be copied at all. I know a little bit of programing but I'm not very experienced with bat scripts. Is there an easy fix to make it work the same on both a file and folder?
#echo off
rem set this to whatever you like
set "BackupFolderName=_OLD"
rem splits filename into name and extension etc for processing
set "OutputFolder=%CD%\%BackupFolderName%"
set "FullPath=%~1"
set "Filename=%~n1"
set "Ext=%~x1"
rem creates an output folder if none exist
if not exist "%OutputFolder%" mkdir "%OutputFolder%"
rem find the highest version of the file
set a=1
set pad=00000
:loop
rem leading zeroes
SET b=%pad%%a%
rem %var:~10% gets the sub-string from index 10 to the end of %var%
SET b=%b:~-3%
if exist "%OutputFolder%\%Filename%%b%%Ext%" set /a a+=1 && goto :loop
echo "Backed up %FilenameExt% as %Filename%%b%%Ext% in %BackupFolderName%"
xcopy /s/y "%FullPath%" "%OutputFolder%\%Filename%%b%%Ext%"
rem pause
timeout 1 >nul
exit
Here is my final code that takes multiple files or folders and does a backup of them:
#echo off
setlocal
rem set this output folder name to whatever you like eg _OLD
set "BackupFolderName=_OLD"
rem creates an output folder, if none exist
set "OutputFolder=%CD%\%BackupFolderName%"
if not exist "%OutputFolder%" mkdir "%OutputFolder%"
rem loops through all the files dropped on bat
FOR %%G IN (%*) DO (call :sub %%G)
goto :end
:sub
rem splits filename into name and extension etc for processing
set "FullPath=%~1"
set "Filename=%~n1"
set "Ext=%~x1"
rem rem find the highest version of the file
set a=1
set pad=00000
:loop
rem leading zeroes
SET b=%pad%%a%
rem %var:~10% gets the sub-string from index 10 to the end of %var%
SET b=%b:~-3%
if exist "%OutputFolder%\%Filename%%b%%Ext%" set /a a+=1 && goto :loop
rem rem checks if dropped item is file or folder
set type=invalid
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"d" >nul && set type=folder)
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"-" >nul && set type=file)
rem copies file or folder to destination
if %type%==file (copy "%FullPath%" "%OutputFolder%\%Filename%%b%%Ext%" >nul)
if %type%==folder (xcopy /s/y/q "%FullPath%" "%OutputFolder%\%Filename%%b%%Ext%\" >nul)
echo "Backed up %Filename% as %Filename%%b%%Ext% in %BackupFolderName%"
goto :eof
:end
pause
rem timeout 1 >nul
rem exit
You can check the file attributes (see for /?)
#echo off
setlocal
set type=invalid
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"d" >nul && set type=folder)
for %%F in ("%~1") do (echo/%%~aF|findstr /bc:"-" >nul && set type=file)
echo %type%

How to use a batch file to loop through several executables files to compress them (.7z) and rename the file to avoid ".exe.7z"

I'm trying to zip up 27 exe files in one go using a batch file. The purpose of this file is to create .7z files for a modified HBCD menu. This file is located in, ...\Documents\CD\HBCD\Programs the exe files are in ...\Documents\CD\HBCD\Programs\Files\SysinternalsSuite
I keep getting:
Error:
Incorrect command line
I keep searching around and trying different things but I can't get it to work.
File Name: 7zBatch.bat
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
pushd "%~dp0"
echo "-------------------------------------------------"
echo "||======== BATCH ZIPPER (.7z) for HBCD ========||"
echo "-------------------------------------------------"
:AskSource
echo Enter the location of the exe file(s)
set SOURCE=
set /p SOURCE=">>" %=%
echo "%SOURCE%", is that correct & goto ConfirmSource
:ConfirmSource
echo (Y)es or (N)o?
set INPUT=
set /p INPUT=">>" %=%
if /I "%INPUT%"=="y" goto AskDest
if /I "%INPUT%"=="n" goto AskSource
echo Incorrect input, is the location correct? & goto ConfirmSource
:AskDest
cd %SOURCE%
echo Enter the location of the zip file(s)
set DEST=
set /p DEST=">>" %=%
echo "%DEST%", is that correct & goto ConfirmDest
:ConfirmDest
echo (Y)es or (N)o?
set INPUT=
set /p INPUT=">>" %=%
if /I "%INPUT%"=="y" goto Execute
if /I "%INPUT%"=="n" goto AskDest
echo Incorrect input, is the location correct? & goto ConfirmDest
:Execute
FOR /f "tokens=*" %%G IN ('dir /b *.exe') DO (
set fname=%%G
set nfname=!fname:.exe=!
echo.
echo Found: !fname!
..\..\7z.exe a -t7z !nfname!.7z "!fname!" -mx5 -sdel -oC:%DEST%
timeout /t 10 /nobreak
)
ENDLOCAL
echo.
pause
Once it gets to the 7 Zip line it gives the error. I realized that the nfname variable was empty so I tried:
set nfname=!%%G:.exe=!
That didn't work so I tried deleting that and going with:
..\..\7z.exe a -t7z !fname:.exe=!.7z "!fname!" -mx5 -sdel -oC:%DEST%
That didn't work so I tried putting different things in quotes one by one and then everything:
"..\..\7z.exe" a -t7z "!fname:.exe=!.7z" "!fname!" -mx5 -sdel -oC:"%DEST%"
Still nothing. What am I missing?
#echo off
SETLOCAL
echo "-------------------------------------------------"
echo "||======== BATCH ZIPPER (.7z) for HBCD ========||"
echo "-------------------------------------------------"
:AskSource
echo Enter the location of the exe file(s)
set "SOURCE="
set /p "SOURCE=>>"
echo "%SOURCE%", is that correct
:ConfirmSource
echo (Y)es or (N)o?
set "INPUT="
set /p "INPUT=>>"
if /I "%INPUT%"=="y" goto AskDest
if /I "%INPUT%"=="n" goto AskSource
echo Incorrect input, is the location correct?
goto ConfirmSource
:AskDest
echo Enter the location of the zip file(s)
set "DEST="
set /p "DEST=>>"
echo "%DEST%", is that correct
:ConfirmDest
echo (Y)es or (N)o?
set "INPUT="
set /p "INPUT=>>"
if /I "%INPUT%"=="y" goto Execute
if /I "%INPUT%"=="n" goto AskDest
echo Incorrect input, is the location correct?
goto ConfirmDest
:Execute
FOR %%G IN ("%SOURCE%\*.exe") DO (
"%~dp0..\..\7z.exe" a -t7z "%DEST%\%%~nG.7z" "%%~fG" -mx5 -sdel
)
ENDLOCAL
echo.
pause
The pushd and cd removed. Unsure why 7z.exe would be
located 2 directories up from where the input executable
directory is located. 7z.exe is now located 2 directories
up from the script directory.
The -o switch for 7z.exe is only for extraction as
mentioned in the help file so is omitted.
Double quoted set of variables to avoid any trailing spaces.
The for loop changed to simple type as it gives the file
paths required without need of using dir.
EnableDelayedExpansion removed as the for variables
uses modifiers to get fullpath, name, drive etc. See
for /? about modifiers available.
Removed timeout as it complains if stdin is used and see
no reason to use it for this task.
Removed obsolete goto commands that go to the next line
with a command.

How do I make a batch log file?

How do I make a log file from this code. This has been answered a ton, but this file is huge and I want a simple log file. As you see I also tried to add a log file names RandomNamesLog.log. See if the output goes there.
I want all the code to be outputted into the log file, with error messages and confirm messages, like removing the #ECHO OFF value.
If you need more on what I want, please tell me.
#ECHO OFF
SETLOCAL EnableDelayedExpansion for /F "tokens=1,2 delims=#" %%a in
('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do ( set
"DEL=%%a" )
ECHO Random Names
ECHO Written By: Trevor T
ECHO UltimateGuidesPro.blogspot.com
ECHO.
ECHO.
REM Randomly renames every file in a directory.
SETLOCAL EnableExtensions EnableDelayedExpansion
REM 0 = Rename the file randomly.
REM 1 = Prepend the existing file name with randomly generated string.
SET PrependOnly=0
REM 1 = Undo changes according to the translation file.
REM This will only work if the file "__Translation.txt" is in the same
folder.
REM If you delete the translaction file, you will not be able to undo
the changes!
SET Undo=0
REM --------------------------------------------------------------------------
REM Do not modify anything below this line unless you know what you are doing.
REM --------------------------------------------------------------------------
SET TranslationFile=_TranslatonData.txt
SET LogFile=_RandomNamesLog.log
IF NOT {%Undo%}=={1} (
REM Rename files
ECHO You are about to randomly rename every file in the following folder:
ECHO %~dp0
ECHO.
ECHO A file named %TranslationFile% will be created which allows you to undo this.
ECHO Warning: If %TranslationFile% is lost/deleted, this action cannot be undone.
ECHO Type "OK" to continue.
SET /P Confirm=
IF /I NOT {!Confirm!}=={OK} (
ECHO.
ECHO Aborting.
GOTO :EOF
)
ECHO Original Name/Random Name > %TranslationFile%
ECHO ------------------------- >> %TranslationFile%
FOR /F "tokens=*" %%A IN ('DIR /A:-D /B') DO (
IF NOT %%A==%~nx0 (
IF NOT %%A==%TranslationFile% (
SET Use=%%~xA
IF {%PrependOnly%}=={1} SET Use=_%%A
SET NewName=!RANDOM!-!RANDOM!-!RANDOM!!Use!
ECHO %%A/!NewName!>> %TranslationFile%
RENAME "%%A" "!NewName!"
ECHO ----------------------------------------------------- >> %TranslationFile%
ECHO Designed by Trevor T | UltimateGuidesPro.blogspot.com >> %TranslationFile%
ECHO. >> %TranslationFile%
ECHO WARNING: THIS FILE REQUIRED TO UNDO RANDOM NAMING! THE FILE CAN BE MOVED AS LONG AS IT IS IN THE FOLDER WHEN USING THE UNDO RANDOM NAMES FUNCTION! >> %TranslationFile%
ECHO +---------+
ECHO | Credits |
ECHO +---------+
Echo.
ECHO Original Random Names script created by
call :colorEcho 0a "Jason Faulkner"
call :colorEcho 0a "HowToGeek.com"
ECHO ---------------------------------------
ECHO Script created by
call :colorEcho 0a "Trevor T"
ECHO -------------------------------------------
ECHO Color Text system created by
call :colorEcho 0a "Visual Magic, user on Stack Exchange"
ECHO Type "Exit" to quit
GOTO :Exit
:Exit
SET /P Confirm=
IF /I NOT {!Confirm!}=={Exit} (
ECHO.
ECHO Please try again
GOTO :Exit2
Exit
:Exit2
SET /P Confirm=
IF /I NOT {!Confirm!}=={OK} (
ECHO.
ECHO Please try again
GOTO :Exit
)
)
)
) ELSE (
ECHO UNDO MODE
IF NOT EXIST %TranslationFile% (
ECHO Missing translation file: %TranslationFile%
ECHO Please make sure %TranslationFile% is in the location of the random files. Otherwise it will give this error.
PAUSE
GOTO :EOF
)
ECHO Undoing...
FOR /F "skip=2 tokens=1,2 delims=/" %%A IN (%TranslationFile%) DO RENAME "%%B" "%%A"
DEL /F /Q %TranslationFile%
ECHO Completed Undo!
Pause
)
Exit
REM This is the color text code. Don't touch this, unless you know a better way to use color text.
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i
I have rewritten your script fixing all of the problems I could see and removing the pointless code to add colored text.
Test it to see if it works as it should adding whatever you think I've missed.
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
ECHO Random Names
ECHO Written By: Trevor T
ECHO UltimateGuidesPro.blogspot.com
ECHO.
REM Randomly renames every file in a directory.
REM 0 = Rename the file randomly.
REM 1 = Prepend the existing file name with randomly generated string.
SET "PrependOnly=0"
REM 1 = Undo changes according to the translation file.
REM This will only work if the file "_TranslationData.txt" is in the same folder.
REM If you delete the translaction file, you will not be able to undo the changes!
SET "Undo=0"
REM --------------------------------------------------------------------------
REM Do not modify anything below this line unless you know what you are doing.
REM --------------------------------------------------------------------------
SET "TranslationFile=_TranslationData.txt"
IF "%Undo%"=="1" GOTO UNDOIT
ECHO You are about to randomly rename every file in the following folder:
ECHO %CD%
ECHO.
CHOICE /M "Do you want to continue "
IF NOT %ERRORLEVEL%==1 (
ECHO.
ECHO Aborting.
TIMEOUT -1
GOTO :EOF
)
ECHO A file named %TranslationFile% will be created which allows you to undo this.
ECHO Warning: If %TranslationFile% is lost/deleted, this action cannot be undone.
(
ECHO ;Original Name/Random Name
ECHO ;-------------------------
FOR %%A IN (*) DO IF NOT "%%A"=="%~nx0" IF NOT "%%A"=="%TranslationFile%" (
SET "Use=%%~xA"
IF "%PrependOnly%"=="1" SET "Use=_%%A"
SET "NewName=!RANDOM!-!RANDOM!-!RANDOM!!Use!"
ECHO %%A/!NewName!
REN "%%A" "!NewName!"
)
ECHO ;-----------------------------------------------------
ECHO ;Designed by Trevor T ^| UltimateGuidesPro.blogspot.com
ECHO.
ECHO ;WARNING: THIS FILE REQUIRED TO UNDO RANDOM NAMING!
ECHO ; THE FILE CAN BE MOVED AS LONG AS IT IS IN THE FOLDER WHEN USING THE UNDO RANDOM NAMES FUNCTION!
)>"%TranslationFile%"
ECHO +---------+
ECHO ^| Credits ^|
ECHO +---------+
ECHO.
ECHO Original Random Names script created by Jason Faulkner # HowToGeek.com
ECHO -------------------------------------------
ECHO Script created by Trevor T
ECHO -------------------------------------------
TIMEOUT -1
GOTO :EOF
:UNDOIT
ECHO UNDO MODE
IF NOT EXIST "%TranslationFile%" (
ECHO Missing translation file: %TranslationFile%
ECHO Please make sure %TranslationFile% is in the location of the random files. Otherwise it will give this error.
TIMEOUT -1
GOTO :EOF
)
ECHO Undoing...
FOR /F "USEBACKQ TOKENS=1-2 DELIMS=/" %%A IN ("%TranslationFile%") DO REN "%%B" "%%A"
DEL /F "%TranslationFile%"
ECHO Completed Undo!
TIMEOUT -1
GOTO :EOF
Once you are happy with it edit your opening question explaining what it is you want to have in the log file and how you need it to look.
I use this. it seems to work.
It just starts a log file and maintains logs.
You can set logpath and logname (base name) then you call this create_logfile
It creates a semi-random log file.
Now you write to the set logfile
I'm not an advanced coder. Please feel free to correct:
#echo off
rem
echo %date% %TIME%
rem Log File Path
if "%logpath%" == "" set logpath=%~dp0
if "%logpath:~-1%" == "\" set logpath=%logpath:~0,-1%
rem Make log file name
if "%logname%" == "" set logname=log
set t=%TIME: =0%
set d=%DATE%
set logfilename=%logname%_%d:~12,2%%d:~4,2%%d:~7,2%%t:~0,2%%t:~3,2%%t:~6,2%.log
set t=
set d=
rem Test
echo full log file name = %logfilename%
echo find base log name = %logfilename:~0,-17%
echo log path = %logpath%
rem Logs to maintain
set /a dellog=5
rem Find file to delete
set var=
set /a cnt=0
set fltodel=
set fstfle=
for %%a in (%logpath%\%logname%*.log) do (
set var=%%a
call set /a "cnt+=1"
echo %%cnt%%| findstr /l "1" >nul && (call set fstfle=%%var%%)
echo %%cnt%%| findstr /l "%dellog%" >nul && (call set fltodel=%%fstfle%%)
)
rem Delete old log
echo file to delete %fltodel%
if exist %fltodel% (del /q %fltodel%) else (echo "%fltodel%" does not exist. nothing to delete.)
echo tryed to delete
rem Create Log File and logfile attribute
set logfile=%logpath%\%logfilename%
if exist %logfile% (
echo start logging... "%~0" on %date% %time% >> %logfile%
) ELSE (
echo Start Log for "%~0" on %date% %time% > %logfile%
)

Batch || I am having problems loading variables from txt file

I am having problems reading from text files.
When I try to load in variables from text files, they just return blank, but when I 'type' them, they return perfectly normal.
The code I use to read and save the files (basecd is the directory of the bat file):
:loadGame
cls
echo Saves:
cd Data\Saves\
dir /a:d /b
echo[
cd %~dp0
echo %~dp0
set /p filename=Name of save file:
echo[
if "%filename%" EQU "" (
echo File does not exist...
pause
goto menuLoop
)
if exist "Data/Saves/%filename%" (
cd %basecd%Data\Saves\%filename%\
echo %basecd%Data\Saves\%filename%\
echo Loading File...
set /p name=<%basecd%Data\Saves\%filename%\name.txt
set /p race=<%basecd%Data\Saves\%filename%\race.txt
set /p hair=<%basecd%Data\Saves\%filename%\hair.txt
set /p eyes=<%basecd%Data\Saves\%filename%\eyes.txt
set /p area=<%basecd%Data\Saves\%filename%\area.txt
set /p quest_starter=<%basecd%Data\Saves\%filename%\quest_starter.txt
type %basecd%Data\Saves\%filename%\area.txt
echo %name%
echo %quest_starter%
echo %area%
echo File loaded
pause
goto mainLoop
)
echo File does not exist...
pause
goto menuLoop
This is the code that I use to write to the files, but I can see on my computer that the files are in the folder and are not empty.
:event_generic_save_game
cls
echo Save file name:
:saveloop
set /p filename=
if "%filename%" EQU "" (
echo File name is invalid!
goto saveloop
)
if exist "Data\Saves\%filename%" (
echo Save file already exists.
set /p input=Overwrite? y/n
if "%input%" EQU "n" (
echo Save canceled
set /p buffer=
cls
goto mainLoop
)
)
echo saving game '%filename%'...
if exist "Data\Saves\%filename%" (
del Data\Saves\%filename%
)
mkdir Data\Saves\%filename%
echo %area%>Data\Saves\%filename%/area.txt
echo %hair%>Data\Saves\%filename%/hair.txt
echo %eyes%>Data\Saves\%filename%/eyes.txt
echo %race%>Data\Saves\%filename%/race.txt
echo %name%>Data\Saves\%filename%/name.txt
echo %quest_starter%>Data\Saves\%filename%/quest_starter.txt
echo Game saved
pause
cls
goto mainLoop
'set /p buffer=' Is a stand in for 'pause'
Please help, I have been ruminating on this for days and I can't get over it.
Thank you for reading
Please note that \ is the path-separator in batch, and / introduces swiches. Sometimes batch does the translation. Not always....
This has nothing to do with your apparent problem. Please see endless items on SO about delayed expansion
Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
In your case, you are varying the values within the block, hence you see the original values, not the altered values.
Tip for game-generation:
If you reserve a character as a prefix for variables-you-want-to-save (eg all variables I want to save/reload start with #) then all you need to save a game is
set #>"mygamefile.txt"
and all you need to reload a game is
for /f "usebackqdelims=" %%a in ("mygamefile.txt") do set "%%a"
To zap all # variables (useful before reloading a game) use
for /f "delims==" %%a in ('set # 2^>nul') do set "%%a="

CMD to flatten a directory using cmd - but keeping files if the name occurs more than once [duplicate]

So, here's what I have: I created a small batch file to record the results of a ping test to a text file. What I want to do is run the batch file and move the results log to a specific folder on the Desktop automatically. Then, if the target filename exists, automatically rename accordingly. Meaning, if File1 exists, create File2, File3, so on and so forth. Here's what I have so far:
#echo off
color A
title Ping Test
:A
echo.
cls
ping google.com -n 4 > C:\Users\%username%\Desktop\pingresults.txt
cls
:Question
echo.
echo You can find the results in C:\Users\%username%\Desktop\pingresults.txt
echo Would you like to run this test again? (Y/N)
Set /p Choice=
if %choice% equ y goto :A
if %choice% equ n goto :Results
if %choice% neq y goto :Question
if %choice% neq n goto :Question
:Results
cls
echo Would you like to view the results of the test? (Y/N)
Set /p Choice=
if %choice% equ y goto :OpenResults
if %choice% equ n goto :Close
if %choice% neq y goto :Results
if %choice% neq n goto :Results
:Close
exit
:OpenResults
start C:\Users\%username%\Desktop\pingresults.txt
And the move batch file looks like this:
#echo off
echo.
cd C:\Users\Diesel\Desktop
move pingresults.txt PingResults\
if exist pingresults.txt ren pingresults.txt=+1
Exit.
I don't want to overwrite the existing file, but rename it in succession. I can't find any helpful articles anywhere using only batch files, they all say to use vbs or php, a language I'm not familiar with
To rename files to file1 [file2][...] and move it in a desktop folder:
#ECHO Off &SETLOCAL
FOR %%a IN (*.txt) DO CALL:processFile "%%~a"
goto:eof
:processFile
SETLOCAL
:loop
SET /a fileCounter+=1
SET "fileName=%~n1%filecounter%%~x1"
IF EXIST "C:\Users\%username%\Desktop\%fileName%" GOTO:loop
ECHO MOVE "%~1" "C:\Users\%username%\Desktop\%fileName%"
ENDLOCAL
goto:eof
Look at the output and remove the word echo before move if it looks good.
I have a pair of utility files that do this, so I can call from either command line, or another batch file. This manages several versions of the file in the same folder, and I would call it before moving your new file in.
Usage is:
archivefile 5 "c:\temp\songs" .txt [move]
Where 5 is the number of versions to keep.
The base file name in this example is "c:\temp\songs.txt"
and it creates (in c:\temp) 5 files: songs_1.txt songs_2.txt songs_3.txt songs_4.txt songs_5.txt
If you specify move it will move the original songs.txt otherwise it copies it.
Note, if you're using it from another batch file (which you'll probably want to), you need to use call or it won't return to your original batch file (both batch files will exit instead, which isn't what you want):
call archivefile 5 "c:\temp\songs" .txt
You need the pair of batch files to be either in the current directory, or on the windows path. Now I think about it, archivefile_b.bat could probably be a sub-routine within the main file instead, but it ain't broke, so I'm not going to fix it.
This is archivefile.bat:
#Echo off
rem archivefile.bat - keep a number of archives of a file
rem paramters: n rootfile extension [move|copy]
rem n = number of files to keep.
rem move|copy optional indicator to rename (move) the original file instead of copying it
rem archivefile 5 "c:\temp\songs" .txt [move]
rem
if "%3"=="" goto usage
set _af_n=%1
set _af_root=%2
set _af_ext=%3
set _af_move=copy
set _af_moveX=%4
if "%_af_moveX%"=="move" set _af_move=move
set _af_i=
set _af_j=
rem make sure that the first parameter (n) is numeric
set /A _af_n=%_af_n%
if "%_af_n%"=="0" echo Error: number of copies must be numeric (%1) & goto usage
if not exist %_af_root%%_af_ext% echo Error: cannot locate main file: %_af_root%%_af_ext% & goto error
rem remove the oldest file
if exist %_af_root%_%_af_n%%_af_ext% del %_af_root%_%_af_n%%_af_ext%
rem move up the remainder
for /L %%i in (%_af_n%, -1, 1) do call archivefile_b %%i %_af_root% %_af_ext%
rem copy the original
if "%_af_move%"=="move" goto moveIt
rem move not specified - make a copy
copy %_af_root%%_af_ext% %_af_root%_1%_af_ext%
goto moveCopyDone
:moveIt
rem need filename only for a rename
set _af_destfile=%_af_root%_1%_af_ext%
set _af_destfile=%_af_destfile:"=%
for %%i in (%_af_destfile%) do set _af_destfile=%%~ni%%~xi
ren %_af_root%%_af_ext% %_af_destfile%
:moveCopyDone
dir %_af_root%*%_af_ext%
goto done
:usage
echo usage: archivefile n rootfile extension
echo - n = number of archives to keep
echo - rootfile = the root filename
echo - extension = file extension
echo.
echo example:
echo archivefile 5 "c:\Documents and Settings\gregh\My Documents\Rescued document" .txt
goto done
:error
rem could maybe do something here? naa.
goto done
:done
This is archivefile_b.bat, which manages just one of the files:
rem #Echo off
rem archivefile_b.bat - helper for the archivefile routine
rem -- juggles ONE of the archive files.
rem paramters: n rootfile extension
rem n = the index to move from n to n+1
rem archivefile 5 "c:\temp\songs" .txt
rem therefore renames c:\temp\songs_5.txt to c:\temp\songs_6.txt
set _afb_n=%1
set _afb_root=%2
set _afb_ext=%3
rem make sure that the first parameter (n) is numeric
set /A _afb_n=%_afb_n%
if "%_afb_n%"=="0" echo Error: (archivefile_b) number of copies must be numeric (%1) & goto done
set /A _afb_j=%_afb_n%+1
rem define the file names
set _afb_fn=%_afb_root%_%_afb_n%%_afb_ext%
set _afb_fj=%_afb_root%_%_afb_j%%_afb_ext%
rem remove the quotes
set _afb_fn=%_afb_fn:"=%
set _afb_fj=%_afb_fj:"=%
rem can only supply a filename to the ren command (not path)
for %%i in (%_afb_fj%) do set _afb_fj=%%~ni%%~xi
rem do the rename now
if exist "%_afb_fn%" ren "%_afb_fn%" "%_afb_fj%"
:done

Resources