Looking for a script to rename multiple files with charactares already in filename - file

I have many files in many folders that I need to rename.
And example is
from cgs2016-09-05-05-40-34.xls
to cgs0905.xls
and
from cgs2016-09-06-05-40-34
to cgs0906.xls
etc
Any help would be greatly appreciated!

#Jamaz Try out the following code below on a sample of your files. Again please use it on a test sample of your files so it does not cause you issues if it makes a mistake. Thank you and please up-vote if this works for you.
setlocal enabledelayedexpansion
REM Collect list of file names in current directory that have the .xls file extension. Output to text file.
dir /b "*.xls" >xls.txt
REM For loop examines the text file for individual file names.
FOR /F "tokens=1" %%# in (.\xls.txt) do (
REM SET variable "#" to equal "token"
Set "token=%%#"
REM Extract the first 3 characters (year) from the file name and set is to variable "token"
Set "tokenchar=!token:~0,3!"
REM Extract the month characters from the file name and set the variable as "tokenmonth"
Set "tokenmonth=!token:~8,2!"
REM Extract the day characters from the file name and set the variable as "tokenday"
Set "tokenday=!token:~11,2!"
ren "%%#" "!tokenchar!!tokenmonth!!tokenday!.xls"
echo %%#
)
Pause

not the best way, but works for your examples:
#echo off
setlocal enabledelayedexpansion
for %%x in (*.xls) do (
set "filename=%%x"
ECHO ren "%%x" "!filename:~0,3!!filename:~8,2!!filename:~11,2!.xls"
)
remove the ECHO if output is ok.

Because the last nineteen characters, date and time stamp, are more likely to be constant than the first three, (especially over multiple folders), I'd change both the previous answers to cater for that rationale.
#Echo Off
SetLocal EnableDelayedExpansion
(Set _rf=C:\Users\jamaz\TestDir)
(Set _fe=xls)
If Not Exist "%_rf%\" Exit/B
For /R "%_rf%" %%I In (*.%_fe%) Do (Set "_fn=%%~nI"
Echo=Ren "%%I" "!_fn:~,-19!!_fn:~-14,2!!_fn:~-11,2!%%~xI")
Timeout -1 1>Nul
EndLocal
Exit/B
As the OP was not clear about whether the code was for multiple same level folders or subfolders rooted from a single location, I went for the latter as the previous responses had already covered that.
Change your chosen file path and extension on lines 4 and 5
If you are happy with the console output, remove echo= from line 10 and delete line 11

Related

How to batch transfer rename?

There are two folders holding equal amounts of files between them.
I'd like to apply the names from one set ; to the other set of files in no particular order. Inherit the name, but retain the extension .
Input files are .bmp Output files are .ini ( has a gear symbol ).
Example :
folder 1- Flowers.bmp ; folder 2- blank.ini
. To this:
folder 1- Flowers.bmp ; folder 2- Flowers.ini
There would be more files , but equal .
The .ini files are all copies . So they may have a generic name and numbered if that matters to know . Those would all receive one name each from the other .bmp files in the other folder.
Normally I have both folders situated on the Desktop .
I make sure both folders have equal number of files between them . That would be a constant .
I'm trying to stream line some menial repetitive daily tasks .
I did search and what I have found does not really help.
#ECHO OFF
SET "vers=%~1"
IF "%vers%" == "" SET /P "vers=Enter Vers: "
FOR %%F IN (file_XX_*.*) DO CALL :process "%%F"
GOTO :EOF
:process
SET "name=%~nx1"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "name=!name:_XX_=_%vers%_!"
RENAME %1 "%name%"
ENDLOCAL
Hoping to find a solution to this finally .
Ok, here is a slightly long version, but it makes sure it gets the content of each folder.
Note You must ensure that the path to both folders are correctly specified in the third and fourth line:
#echo off
setlocal enabledelayedexpansion
set "source=%userprofile%\Desktop\folder 1"
set "destination=%userprofile%\Desktop\folder 2"
set /a num=0
for %%a in ("%source%\*") do (
set /a num+=1
set "fr!num!m=%%~na"
)
set /a oldn=!num!
set /a num=0
for %%b in ("%destination%\*") do (
set /a num+=1
set "to!num!r!=%%~nxb"
set "ext=%%~xb"
)
pushd "%destination%"
for /l %%i in (1,1,!oldn!) do ren "!to%%ir!" "!fr%%im!%ext%"
popd
pause
You can remove pause at the bottom of the script, once you are happy with the output.
This is not the most effective way, but considering your limited batch experience, I guess an understandable approach is better than an optimized one (using array-like variables).
#echo off
setlocal enabledelayedexpansion
(for %%A in ("folder 1\*.bmp") do echo %%~nA)> "%temp%\names.txt"
<"%temp%\names.txt" (
for %%A in ("folder 2\*.ini") do (
set /p "name="
ECHO ren "%%A" "!name!.ini"
))
The first for loop creates a list of the desired names (from Folder 1). The modifier %%~nA returns the name only.
The second for processes each file in Folder 2 and takes a name from the previously generated file for each file. This depends on the fact that the number of files in both folders are the same, else you may get undesired results.
I disabled the actual ren command by just echoing it. Check the output and only when you are satisfied, remove the ECHO.

Batch programing to search some file in sub folders

I have hundreds of csv files . csv files are stored in folders and sub ​​folders . I want to search fifty csv file whose file names have been determined , for example 1.csv , 2.csv , 3.csv , ... , 50.csv . very troublesome if I searched one by one using the Windows search tool . I would like if the files are found , save in the folder named FOUND . please help to overcome this problem by using the batch programming / bat ? thank you very much
There's a number of approaches one can take, depending on how much automation you require... To help you get started, you may want to look at this it helped me (and indeed continues to do so) when I started learning batch. Furthermore I will provide one possible template for achieving your objective, as I have interpreted it. Perhaps it is not the most elegant or efficient method, but it introduces a number of batch commands that you may or may not have encountered, which in turn may help you develop your own method.
#echo off
setlocal enabledelayedexpansion
echo Please enter a drive letter:
set /p "drive=>"
echo Please enter a search string:
set /p "searchstring=>"
echo %searchstring%>search.txt
set /p search=<search.txt
set /a suffix=0
echo.>>search.txt
:LOOP
for /f "tokens=*" %%i in ("search.txt") do (
set /a suffix=suffix+1
set seq=%search% !suffix!
echo !seq!>>search.txt
)
if !suffix! leq 49 goto LOOP
for /f "tokens=*" %%i in (search.txt) do (
for /f "tokens=*" %%j in ('dir /b /s /a-d %drive%:\"%%i.csv" 2^>nul') do (
if not exist "%~dp0\found" md "%~dp0\found"
move /y "%%j" "%~dp0\found\%%~nxj"
)
)
pause
This is not intended as a definitive solution, though you may find it answers your original query/request. All the best.
Here's another working solution for you..
#ECHO OFF
SETLOCAL EnableDelayedExpansion
REM First Set your directories input and output
SET InputDir=C:\Directory to your CSV files\
SET OutputDir=C:\Directory to your CSV files\FOUND
REM check if the FOUND directory exist, if not, then create it.
IF NOT EXIST OutputDir (
mkdir %OutputDir%
)
REM Grab a scan of the input directory and save it to a temporary file list.
Dir /a /b %InputDir%>"%OutputDir%\Found.txt"
REM Set the files you would like to find.
SET "File1=1.csv"
SET "File2=2.csv"
SET "File3=50.csv"
REM The loop, to process the matching file(s).
FOR %%A IN (%File1%,%File2%,%File3%) DO (
FOR /F "usebackq" %%B IN ("%OutputDir%\Found.txt") DO (
IF %%A==%%B (
copy "%InputDir%\%%A" "%OutputDir%\%%A"
)
)
)
REM Clean up the temp file list.
DEL "%OutputDir%\Found.txt"
Make note, I didn't add quotes to the Input and Output variables, but instead added quotes to the copy portion of the code to compensate for white spaces in your directory path. I tried to keep it simple, so you could follow the logic of how it processed what you are looking for, you can now modify this to your liking.. Have fun. Cheers!

How do I exclude specific file names from an MS DOS dir list?

I am creating an MS DOS batch script that needs to list every .bat file in the current directory, but not show autoexec.bat or other utilities or systems .bat files that shouldn't be run by the user.
I currently have DIR "*.bat" /B /P
This lists all .bat files appropriately, but it shows autoexec.bat. How would I exclude that from the list? Also slightly important, how could I chop off the file extensions and show more than the 7-characters DOS limits files to?
Constraints: I am not able to use a DOS version above WinME. That is the version I am using.
Thanks for any help.
EDIT:
There is plenty of information on the internet about doing this, but it is all in the windows command processor, not MS DOS. Please understand that DOS and the Command Prompt are not the same thing.
#echo off
setlocal EnableDelayedExpansion
rem Add more names separated with slashes here:
set exclude=/autoexec/
for %%a in (*.bat) do (
if "!exclude:/%%~Na/=!" equ "%exclude%" (
echo %%~Na
)
)
EDIT: Some explanations added
Batch file processing is slow, so you should use techniques that allows a Batch file to run faster. For example:
Try to use the minimum lines/commands to achieve a certain result. Try to avoid external commands (*.exe files) like find, findstr, fc, etc. specially if they work on small amounts of data; use if command instead.
Use for %%a in (*.bat)... instead of for /F %%a in ('dir /B *.bat').... The second method requires to execute cmd.exe and store its output in a file before for command can process its lines.
Avoid pipes and use redirections instead. A pipe require the execution of two copies of cmd.exe to process the command at each side of the pipe.
A simple way to check if a variable contain a given string is trying to delete the string from the variable: if the result is different then the string exists in the variable: if "!variable:%string%=!" neq "%variable%" echo The string is in the variable.
Previous method may also be used to check if a variable have anyone of a list of values: set list=one two three, if "!list:%variable%=!" neq "%list%" echo The variable have one value from the list. If the values of the list may have spaces, they must be separated by another delimiter.
EDIT: New version added as answer to new comments
The easiest way to pause one page at a time is to use more filter this way:
theBatchFile | more
However, the program must reorder the output in order to show it in columns. The new version below achieve both things, so it does not require more filter; you just need to set the desired number of columns and rows per page.
#echo off
setlocal EnableDelayedExpansion
rem Add more names separated with slashes here:
set exclude=/autoexec/
rem Set the first two next variables as desired:
set /A columns=5, rows=41, wide=(80-columns)/columns, col=0, row=0
rem Create filling spaces to align columns
set spaces=
for /L %%a in (1,1,%wide%) do set spaces= !spaces!
set line=
for %%a in (*.bat) do (
if "!exclude:/%%~Na/=!" equ "%exclude%" (
rem If this column is less than the limit...
set /A col+=1
if !col! lss %columns% (
rem ... add it to current line
set name=%%~Na%spaces%
set "line=!line!!name:~0,%wide%! "
) else (
rem ... show current line and reset it
set name=%%~Na
echo !line!!name:~0,%wide%!
set line=
set /a col=0, row+=1
rem If this row is equal to the limit...
if !row! equ %rows% (
rem ...do a pause and reset row
pause
set row=0
)
)
)
)
rem Show last line, if any
if defined line echo %line%
Antonio
attrib +h autoexec.bat
should hide autoexec.bat and it should thus not appear in the list
DIR "*.bat" /B /P | find /v "autoexec" | for %i in (*.bat) do #echo %~ni
Using for to process each file name individually:
setlocal enabledelayedexpansion
for /f %%i in ('dir "*.bat" /b') do (
set system=0
if "%%i"=="autoexec.bat" set system=1
if "%%i"=="somesystem.bat" set system=1
if !system!==0 echo %%i
)
Another method without variables:
for /f %%i in ('dir "*.bat" /b') do call :test %%i
goto continue
:test
if "%1"=="autoexec.bat" goto :eof
if "%1"=="somesystem.bat" goto :eof
echo %1
goto :eof
:continue
For both, you can add new filenames to exclude from the list.

Filenames renaming using .bat?

Heythere.
I need your guys help with file renaming using a .bat file.
I got multiple files that I need to be cropped after specified character number.
For exmample, I want to crop name of the files after their fifth character, this way
filename.exe > filen.exe
anothername.exe > anoth.exe
absolutelydifferentname.exe > absol.exe
And, if possible, I'd like to know how to do the opposite. I mean, leaving the certain # of characters at the end, cropping from the beginning of the filename.
Thank you.
If you want to do it in a batch file, the following should work:
#echo off
setlocal ENABLEDELAYEDEXPANSION
for %%i in (<Directory name here>\*) do (
set filename=%%~ni
ren "%%~i" "!filename:~0,5!%%~xi"
)
endlocal
If you wish to change the number of characters used to construct the final filenames, change the "5" in ren "%%~i" "!filename:~0,5!%%~xi".
To take the last 5 characters try: ren "%%~i" "!filename:~-5!%%~xi"
For all except the first 5 characters: ren "%%~i" "!filename:~5!%%~xi"
The Iridium solution will fail if any file name contains the ! character because expansion of %%i will fail if value contains ! and delayed expansion is enabled. This is easily fixed by toggling delayed expansion on and off within the loop.
The explicit disabling of delayed expansion at the top is normally not needed. But it is possible for delayed expansion to already be enabled at the start of a batch file, so I included it just to be safe.
#echo off
setlocal disableDelayedExpansion
for %%F in ("<Directory name here>\*") do (
set "full=%%F"
set "name=%%~nF"
set "ext=%%~xF"
setlocal enableDelayedExpansion
ren "!full!" "!name:~0,5!!ext!"
endlocal
)
Just incase this is a once-off, or some other manual scenario, have a look at
CKRename

Rename multiple images in a folder using a batch file

I have a folder full of images which have a format filename.com_XXX_IMG_000.jpg. The issue comes because the file name has a .com in it, it confuses the the software that I am using to upload it to a webspace.
I need to create a batch file that gets all the images in a folder and renames all of them from filename.com_XXX_IMG_000.jpg => filename_XXX_IMG_000.jpg.
Any help would be greatful, thanks in advance.
Since you want to do it in a batch file:
#echo off
for /f "delims=. tokens=1,2,3" %%f in ('dir /b *.jpg') do (
setlocal enabledelayedexpansion
set part=%%g
if "!part:~0,3!"=="com" (
set oldname=%%f.%%g.%%h
set newname=%%f.!part:~4!.%%h
echo "!oldname!" -^> "!newname!"
ren "!oldname!" "!newname!"
)
endlocal
)
A few notes
for loop variables are single letter, like this: %f
in a batch file, the % must be escaped, so %f becomes %%f
delims=. splits the filenames at the ., in your case into three parts
tokens=1,2,3 returns three variables containing the individual name parts (%f, %g and %h)
enabledelayedexpansion switches on dynamic variable handling
you can do string manipulation with variables: %foo:~0,3% returns the first three characters of %foo%.
with delayed expansion enabled, you can access variables that change their values by using ! instead of %
the > must be escaped or echo won't print it, hence ^>
read some more on String Manipulation in DOS
read HELP FOR and try the following....
#echo off
setlocal enabledelayedexpansion
for %%a in (*.jpg) do (
set fn=%%~na
set fn=!fn:.com=!
echo REN "%%a" "!fn!.jpg"
)
you need to enable delayed expansion because you need to expand a variable inside the for loop.
the loops iterates over all the jpg files in the current directory and for each file it extracts its filename using the ~n syntax, and then it removes all the occurences of .com by replacing them with an empty string. Read HELP SET
after careful testing, remove the echo command

Resources