Filenames renaming using .bat? - batch-file

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

Related

Using Windows ren command to remove ! from filename

I have a bunch of files that are in the following format
filename-!#.ext
where # is an incrementing number to prevent collisions. I would like to just remove the ! from the filename so it reads as
filename-#.ext
It seems like I could do this with the ren command and wildcards but having a hard time getting it to work. I tried running this:
ren *!?.ext *?.ext
My thought is the * should match the filename- part, then !, then the ? for the numeric. However, the resulting file is named this:
filename-!#.ext.ext
and I can't quite figure out why.
The filename part can be dynamic, but won't contain any !'s. Any ideas?
I think you'll have to resort to a small batch file for this:
#echo off
setlocal
for %%a in (*!*.ext) do call :remove "%%~a"
goto :eof
:remove
set "FROM=%~1"
set "TO=%FROM:!=%"
ren "%FROM%" "%TO%"
goto :eof
The above will – for all files containing an exclamation mark and extension ext – call the remove function. This takes the original name (FROM) and determines the new name (TO) by using the %var:find=replace% syntax to remove any exclamation mark (replaces it with an empty string).
Notes
You cannot use find/replace with either %%a or %0 type variables, so you have to assign it to a named variable first.
I originally tried doing this "inline" with the for statement (e.g. for ... ( ending )) but to do that, you would have to enable delayed-expansion (because you would need to access a named variable in a loop). However, delayed-expansion uses ! (instead of %) to reference variables and this got in the way of the ! we were trying to remove. There may be a way of doing this, but I haven't found it. Using call will be slightly slower, but not significantly unless you've got thousands of files.
You don't really need to create TO (you could perform the replacement on the ren command-line) but I used it for clarity.
This will work for all files with an exclamation mark: it doesn't check the bit after is numeric.
I think it is not a good idea to let rename select the files, but instead do it with a for-loop and then execute the rename for every file:
for %%F in (*!*) do (
set "nxF=%%~nxF"
call ren "%%nxF%%" "%%nxF:!=%%"
)
You really have to use call here instead of delayedExpansion, because delayedExpansion would destroy the rename-arguments (because they contain !)
Based upon your provided information and just for the sake of offering something a little different, you could let delayed expansion do the work for you, (as it will remove the unwanted exclamation mark for you).!
#For %%A In ("*-!?.ext") Do #Set "_=%%A" & SetLocal EnableDelayedExpansion & Ren "!_!" "%%A" & EndLocal
You could probably also do it with a nested for loop:
#For %%A In ("*-!?.ext") Do #For /F "Tokens=1*Delims=!" %%B In ("%%A") Do #Ren "%%A" "%%B%%C"
…and from the Command Prompt:
For %A In ("*-!?.ext") Do #For /F "Tokens=1*Delims=!" %B In ("%A") Do #Ren "%A" "%B%C"

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

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

Batch - Looping in 'FileNames_Constant.Ext' , and Print 'FileNames' as an Output

I've got some *.Xml files in a directory and its sub-directories. I need to loop through the XML files which have a specific constant at the end of their file name, and then echo/print their names without the constant part nor the extension (.Xml).
For example: these are the file names I have:
FileAAA_Constant.Xml
FileBBB.Xml
FileCCC.Xml
FileDDD_Constant.Xml
And this is the output I need:
FileAAA
FileDDD
I've tried this command:
For /R %%X in (*_Constant.Xml) do echo %%~nX
Which outputs this:
FileAAA_Constant
FileDDD_Constant
As you can see, it has removed the extension only, while I need to remove "_Constant.Xml" as well.
This works if the file names contains only one underscore, as indicated in your example:
for /F "delims=_" %%X in ('dir /S /B *_Constant.Xml') do echo %%X
If the desired file names may contain more than one underscore, use Pokechu22's answer.
Fairly easy if the exact length of the phrase is known; you just need to use the %var:~0,-3% syntax. Since "_Constant" is 9 chars long, you would want %var:~0,-9%, which takes text from the start (0) to 9 chars from the end (-9). Aditionally, delayed variable expansion also must be enabled with setlocal ENABLEDELAYEDEXPANSION for this to be run inside of your For loop.
Here's a full example:
#Echo off
setlocal ENABLEDELAYEDEXPANSION
for /R %%X in (*_Constant.Xml) do (
set FileNameTemp=%%~nX
echo !FileNameTemp:~0,-9!
)
Note that if you have a file named just _Constant.xml, this will produce "ECHO is off." rather than "" (no output). This can be solved by changing echo !FileNameTemp:~0,-9! to echo. !FileNameTemp:~0,-9!, but that puts a space before each output.
Here's the loop alone:
for /R %%X in (*_Constant.Xml) do (
set FileNameTemp=%%~nX
echo !FileNameTemp:~0,-9!
)

How to change an image tag url in multiple html files using batch script?

There are more than 10 html files with image tags. Every time we deploy our build onto test site we need to change the img source. for eg <img src=/live/Content/xyz.png />
to <img src=/test/Content/xyz.png />.
After looking around and reading for sometime, i have come up with the following batch script, however i cant figure out how do i go further from here :
for /r %%i in (*.html) do echo %%i
for %%f in (*.html) do (
FOR /F %%L IN (%%f) DO (
SET "line=%%L"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "x= <--------------------WHAT DO I SET HERE?
echo %x%
ENDLOCAL )) pause
This is my first batch script, could anyone please guide me in the right direction?
#ECHO OFF
SETLOCAL enabledelayedexpansion
for /r U:\ %%i in (*.html) do (
echo found %%i
SET outfile="%%~dpni.lmth"
(
SETLOCAL disabledelayedexpansion
FOR /F "usebackq delims=" %%L IN ("%%i") DO (
SET "line=%%L"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "line=!line:/live/=/test/!
echo !line!
ENDLOCAL
)
ENDLOCAL
)>!outfile!
)
pause
GOTO :EOF
How about this development?
Notes:
I've modified your FOR/R to ECHO the HTML file being processed and use %%i rather than switching to %%f. U: is my RAMDRIVE; you'd need to modify that to suit.
outfile is set to generate a filename which matches the HTML filename, but with a .lmth extension (can't update in-place) - it gets that from the ~dpn prefixing the i, which means the drive, path and name of the file %%i. It's quoted to take care of potential spaces in the filename or pathname.
The next logical statement is (for /f...[lines] )>!outfile! which sends any echoed text to a NEW file !outfile!. The enabledelayedexpansion in the second physical line of the batch makes !outfile! the RUN-TIME value - as it is changed within the FOR r outer loop.
Since the actual HTML filename in %%i may contain spaces, it needs to be quoted, hence the 'usebackq' clause in the FOR/F. The delims= clause ensures that the ENTIRE line from the file "%%i" is applied to %%L - not just the first token (well, actually, makes the entire line the first token).
The SET command substitutes the string "/test/" for any occurrence of "/live/" in the RUN-TIME value of the variable lineand assigns the result to line. The resultant value is then ECHOd - which is redirected to outfile
Note that in your original, you would be assigning x in the set x= but echo %x% would have reproduced x as it stood when the line was PARSED because batch substitutes the value of any variable for %var% as part of the parsing phase. Consequently, the line would have become simply ECHO (since x would likely be unassigned) and bizarrely would have reported the echo state (Echo is OFF)
A couple of gatchas here. First, % and some other characters are notoriously hard to process with batch, so be careful. Next, FOR/F will bypass empty lines. This can be overcome if required. Third, this will replace ANY occurrence of /live/ in any case with /test/
Good luck!
Edit to support exclamation marks: 20130711T0624Z
Added SETLOCAL enabledelayedexpansion line and ENDLOCAL just before )>!outfile! to match

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