batch file rename files in folder - batch-file

I have multiple text files in a folder that I am searching the content for and renaming the found files but having a problem. When I run the batch it renames all the found files to the same filename. So if it finds 3 files with the string in them it renames all of them to the same file. Still kinda new to this stuff. I am trying to find the string "test1" inside all the text files and then rename the files found to test1.txt, test1 (2).txt, etc.
#ECHO OFF
#SETLOCAL enableextensions disabledelayedexpansion
SET "sourcedir=C:\test"
SET "searchfor=test1"
FOR /f "delims=" %%a IN ('findstr /m /L /c:"%searchfor%" "%sourcedir%\*.txt"') DO (
REN "%%a" "%searchfor%.txt"
)

change
REN "%%a" "%searchfor%.txt"
to
if exist "%searchfor%.txt" (
set "renamed="
for /L %%r in (1,1,100) do if not defined renamed if not exist "%searchfor% (%%r).txt" REN "%%a" "%searchfor% (%%r).txt"&set "renamed=%%r"
) else (
REN "%%a" "%searchfor%.txt"
)
which will for each filename-to-be-changed first detect whether %searchfor%.txt exists, and rename the target file if not. If %searchfor%.txt exists, then set the renamed flag to nothing and loop for %%r = 1 to 100 by steps of 1. If the filename %searchfor% (%%r).txt does not exist, then do the rename and set renamed to (well - any value other than nothing will do - %%r is convenient). Since renamed is now defined, if not defined will be false, so no further rename attempts will be made for that target filename.
(untested)
Note - the syntax is important. Don't try to break the statements over many lines or alter the positions of the parentheses. Just cut-and-paste.
Tip:
Instead of ren use echo ren which will simply REPORT the proposed rename. Obviously, since the file won't actually be renamed, the procedure will report the same new name. Then manually create %searchfor%.txt and try again. Then manually create %searchfor% (1).txt and try yet again. You'll see the proposed new name change. After testing in this manner, change each echo ren to ren and all should proceed smoothly.
(perform tests on a copy with a small number of "hits" to avoid confusion)

Related

How can I add a new line to an already existing section in a .ini file, with batch commands?

I have a file MyFile.ini with a section in it [MySection]
I want to add a new line with a return after it under that section, via a batch file.
Here's the batch file I last tried:
#echo off
Set file=MyFile.ini
Set section=[MySection]
Set newline=MyNewValue=MyNewSetting
for /f "tokens=*" %%l in (%file%) do (
(echo %%l)>> "%file%"
if /i "%%l"=="%section%" (
(echo %newline%)>> "%file%"
)
)
exit
The above has no effect on the ini file.
I want the ini file to go from this:
[MySection]
SomeExistingValue=SomeExistingSetting
To this:
[MySection]
SomeExistingValue=SomeExistingSetting
MyNewValue=MyNewSetting
Any answer will be greatly appreciated because once I can figure this out I can replicate it and add several settings to my file, it's all a bit tedious doing it manually, especially when I do the exact same thing to the exact same file, every time. The file name never changes, the section always exists, the setting I am adding never exists, so all that stuff does not need to be accounted for, nor does making a backup of the file, I can just unzip my backed up file if it gets messed up.
Here's an example based upon my commented methodology:
#Echo Off
Set "file=MyFile.ini"
Set "section=[MySection]"
Set "newline=MyNewValue=MyNewSetting"
Copy /Y "%file%" "%file%.bak">NUL 2>&1||Exit /B 1
(For /F "Tokens=1*Delims=]" %%G In (
'^""%__AppDir__%find.exe" /N /V ""^<"%file%.bak"^"'
)Do If /I "%%H"=="%section%" (Echo=%%H
Echo %newline%)Else Echo=%%H)>"%file%"
Rem Del "%file%.bak"
I have Remarked the last line, because I think it's more important to ensure that the resultant file, %file%, is correct, before you Delete the original, %file%.bak. The choice to do so ultimately lies with yourself.

Create Folder and SubFolder based on file name using batch file

Coding is not my speciality but I have come across a problem and google search has guided me to using batch file process in solving it. Essentially I have a couple of thousands of files that need to be moved into folders and they have a very simple file structure, listed below:
UK--London--Filename.pdf
UK--London--Filename2.pdf
UK--Manchester--Filename3.pdf
UK--Liverpool--Filename4.pdf
UK--Chester--Filename5.pdf
I would like the script to:
1. Pick up the first "--" check if the folder exists, if not create it
2. Pick up the second "--" check if the folder exists, if not create it
3. As there might be more than two "--", ignore the rest
4. Move file into the subfolder
To that end, the output should be some like (note "FILETEST" is the folder I am using to test the script):
C:\FILETEST\UK\London\UK--London--Filename.pdf
C:\FILETEST\UK\London\UK--London--Filename2.pdf
C:\FILETEST\UK\Manchester\UK--Manchester--Filename3.pdf
C:\FILETEST\UK\Liverpool\UK--Liverpool--Filename4.pdf
C:\FILETEST\UK\Chester\UK--Chester--Filename5.pdf
I have had an attempt to re-using a script from another question in stackoverflow (Batch create folders based on part of file name and move files into that folder). I understand that it would not do exactly what I need, but cant seem to get any output.
#ECHO OFF
SETLOCAL
SET "sourcedir=c:\FILETEST"
PUSHD %sourcedir%
FOR /f "tokens=1*delims=--" %%a IN (
'dir /b /a-d *.*.*'
) DO (
ECHO MD %%a
ECHO MOVE "%%a.%%b" --\%%a\
)
POPD
GOTO :EOF
Apologies for any headaches caused, I am hoping this is a simple one to solve.
Thank you,
Panos
#ECHO OFF
SETLOCAL
SET "sourcedir=c:\FILETEST"
PUSHD %sourcedir%
FOR /f "tokens=1,2*delims=-" %%a IN (
'dir /b /a-d *--*--*.*'
) DO if "%%c" neq "" (
ECHO MD "%%a"
ECHO MD "%%a\%%b"
ECHO MOVE "%%a--%%b--%%c" ".\%%a\%%b\"
)
POPD
GOTO :EOF
Read the directory list of files in the current directory, (/a-d = no directorynames) that match *--*--*. Tokenise so that %%a acquires the part before the first --sequence, %%b the second and %%c the remainder.
If %%c is not empty then make the directories ".\%%a" and ".\%%a\%%b" (quoted because any spaces in the name would otherwise be seen as "create two directories") then move the file, again quoted for the same reason.
Note that each character individually between delims= and the close-quote is a delimiter - a delimiter-string is not supported. Consequently, this code will pick up - as well as --- and any other sequence of - and try to process it. You could gate the create/move further by adding if exist "%%a--%%b--%%c" directly after the if "%%c" neq ""before the (.
The md will create a directory if the target name does not already exist, and produce an error-message if it already exists. To suppress the error message, append 2>nul to the md lines.

Batch File to rename filenames from multiple directories

I have multiple *.jpg files located in folders within a main root folder. I'm after a simple batch file that will rename all the files to it's foldername. For example:
Orphan
---Gambia
------GAM001
---------G123.jpg
---------G456.jpg
---------GX12.jpg
------GAM002
---------G789.jpg
---------G012.jpg
---------G112.jpg
And i would like it to look like this:
Orphan
---Gambia
------GAM001
---------GAM001.jpg
---------GAM001 (1).jpg
---------GAM001 (2).jpg
------GAM002
---------GAM002.jpg
---------GAM002 (1).jpg
---------GAM002 (2).jpg
So i'm after a batch file that I can run from the Main Root folder.
Sorry in advance as I am new to all of this and I thought I would give it a go into something that I am finding very interesting!
Thanks in advance
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\orphan"
FOR /d /r "%sourcedir%" %%a IN (*) DO (
PUSHD "%%a"
FOR /f "delims=" %%f IN (
'dir /b /a-d /o-n "%%~nxa*.jpg" 2^>nul'
) DO REN "%%f" "%%f.jpg"
SET /a count=0
FOR /f "delims=" %%f IN (
'dir /b /a-d "*.jpg" 2^>nul'
) DO ECHO REN "%%f" "%%~nxa (!count!).jpg"&SET /a count +=1
IF EXIST "%%~nxa (0).jpg" ECHO REN "%%~nxa (0).jpg" "%%~nxa.jpg"
POPD
)
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
First step is to process the names of the directories, recursively into %%a. These are then pushed (which switches to the nominated directory, %%) and the main process executed before executing a pop to restore the original directory.
The main process first reads the directory for (dirnameanything.jpg) and sorts in reverse-name order to ensure the longest name is first. Then any names found are renamed with an extra ".jpg" This means that if the directory has already been processed, (eg) GAM002.jpg may exist, so it is renamed gam002.jpg.jpg and hence gam002.jpg will not exist after this first rename - and the same goes for gam002 (1) - it is now gam002 (1).jpg.jpg. Even if gam002.jpg.jpg already existed, this method is safe because the renaming is performed in reverse-name order, so gam002.jpg.jpg would have been renamed gam002.jpg.jpg.jpg before an attempt is made to rename gam002.jpg to gam002.jpg.jpg
Next step is the real rename sequence. Each .jpg is listed and then processed, so the original list of files is renamed, avoiding the problem with encountering an already-renamed file. Each one is simply renamed with an increasing count in parentheses after the name of the parent directory.
Finally, "parentdirectoryname (0).jpg" is renamed to "parentdirectoryname.jpg" and all is complete.

Using batch files to remove a single number from a folder name

At work we use a bespoke program to search through a directory tree and find an individual image file. These files are stored in folders that have a 7-digit name, starting with '18' - so for instance '1873456', '1873457', '1873458' etc. The problem I have is at some point last year the procedure that creates these folders and populates the images in them reached '1899999' - and then rolled over to '18100000' and carried on like that for over 4,000 folders before it was caught and corrected.
The bespoke program we use can only handle seven-digit folder names. What I would like to do is create a batch file that renames all the eight-digit folders by removing the extra '1' in the name, so '18100000' becomes '1800000' and so forth until '18104013' becomes '1804013'.
Can anyone help?
Run this in the base folder, it will not change any folders.
A file called renfile.bat.txt will be created that contains the rename command for the folders that match the filespec. Examine it in notepad to see if it is ok and then rename it to renfile.bat and run it.
It's not tested.
#echo off
setlocal enabledelayedexpansion
for /d /r %%a in (18??????) do (
set "name=%%~nxa"
>>renfile.bat.txt echo ren "%%a" "!name:~0,2!!name:~3!"
)
Something like
for /l %%x in (100000,1,104013) do (
set oldsuffix=%%x
set newsuffix=%oldsuffix:~-5%
ren 18%%x 18%newsuffix%
)
setlocal enableextensions enabledelayedexpansion
for /d /r "c:\somewhere" %%f in (181?????) do (
set "name=0" & set /a "name+=%%~nf" 2>nul
if !name! gtr 1899999 ren "%%~ff" "18!name:~-5!"
)

How to use batch job to add the file "create date" into all the files in a directory?

I have a folder that gets a new file added everyday to the folder with the same file name but incremental extension such as .001, .002, .003, etc. However, if there's no file within the folder it starts at .001 again.
The problem is they are all named the same and if I move them to another folder to archive them it would just overwrite the same file over and over again. I could create a folder each day with the date with only one file in it, but that seems a bit redundant.
Is there a way to look at the create date of each file and rename it to the create date?
I've gotten this far, but it looks like for this situation I have to use a static file name, how to loop through the entire directory?
SET filename = C:\test.001
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
rename c:\test.001 C:\test_%filedatetime%.txt
move C:\*.txt C:\archive\
this provides the correct sort order:
#echo off &setlocal disableDelayedExpansion
set "startfolder=%userprofile%\test"
cd /d "%startfolder%"
for %%a in (*) do (
for /f "delims=." %%b in ('wmic datafile where "name='%startfolder:\=\\%\\%%~a'" get lastmodified^|find "."') do (
echo(ren "%startfolder%\%%~a" "%%~b.txt"
)
)
Remove echo to get it working.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "targetdir=c:\sourcedir"
SET "destdir=c:\destdir"
PUSHD "%targetdir%"
FOR %%a IN (*.*) DO (
SET "timestamp=%%~ta"
SET "timestamp=!timestamp:/=_!
SET "timestamp=!timestamp::=_!
SET "timestamp=!timestamp:.=_!
SET "timestamp=!timestamp:,=_!
SET "timestamp=!timestamp: =_!
ECHO MOVE "%%a" "%destdir%\%%~na.!timestamp!"
)
GOTO :EOF
This should work with any file in the nominated target directory where the name does not include ! or ^.
The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)
The gymnastics around timestamp are intende to replace /: with _ since these are illegal filename characters. Space., are similarly replaced - they're legal but often painful.
If you want the destination filename to be name.003.timestamp, remove the ~na from the destination name.
Try like this :
SET $path=The_path_who_contain_the_FILES
FOR /F "DELIMS=" %%f IN ('dir "%$path%" /a-d/b') DO (
SET filedatetime=%%~tf
move "%%~dpnxf" "C:\archive\test_%filedatetime%.txt")

Resources