Solved File Prefix Help

born2achieve

New member
Local time
5:31 PM
Messages
36
Hi,

I need to add the prefix to the files in specific directory. For this i need to input the directory name.

I need to add the prefix "Sample_" to all the txt files in the specified directory

Sample code i tried:
Code:
FOR /f "delims=" %%F IN ("D:\Sample\*.txt")  DO (RENAME "%%F" "Sample_%%F")

but it's not working. any suggestion please
 

My Computer

Computer type
PC/Desktop
OS
windows7 64 bit
Hi Born2achieve,

Here's a sample batch file that will help you achieve what you need.
Code:
@echo off

set prefix="Sample_"
set suffix=""

set location="D:\Sample"
set filemask="*.txt"

pushd "%LOCATION:"=%"
for /f "delims=" %%I in (' dir /a:-d /b "%LOCATION:"=%"\"%FILEMASK:"=%" ') do (
	if not "%~0"=="%%~fI" ren "%%~fI" "%PREFIX:"=%%%~nI%SUFFIX:"=%%%~xI"
)
popd


And to help you identify where you went wrong, here are the two corrected Command Prompt one liners you can compare your line with.
Code:
[COLOR="Silver"]rem[/COLOR] [COLOR="Silver"]Using a For /F loop[/COLOR]
for /f "delims=" %I in (' dir /a:-d /b "D:\Sample\*.txt" ') do ren "%~fI" "Sample_%~nxI"
[COLOR="Silver"]rem[/COLOR] [COLOR="Silver"]Using an ordinary For loop[/COLOR]
for %I in ( "D:\Sample\*.txt" ) do ren "%~fI" "Sample_%~nxI"
 
Last edited:

My Computer

Computer type
PC/Desktop
OS
Windows 10, Windows 8.1 Pro, Windows 7 Professional, OS X El Capitan
thank you gentle man. your batch code worked

is there any way to check if the already starts with "Sample_" and skip in that case adding the prefix.

thanks
 

My Computer

Computer type
PC/Desktop
OS
windows7 64 bit
Absolutely.

Code:
@echo off

set prefix="Sample_"
set suffix=""

set location="D:\Sample"
set filemask="*.txt"

pushd "%LOCATION:"=%"
for /f "delims=" %%I in (' dir /a:-d /b "%LOCATION:"=%"\"%FILEMASK:"=%" ') do (
	if not "%~0"=="%%~fI" (
		echo '%%~nI'| findstr /i "^'%PREFIX:"=%.*%SUFFIX:"=%'$" >NUL || ren "%%~fI" "%PREFIX:"=%%%~nI%SUFFIX:"=%%%~xI"
	)
)
popd
 

My Computer

Computer type
PC/Desktop
OS
Windows 10, Windows 8.1 Pro, Windows 7 Professional, OS X El Capitan
Hi Genleman,

your solution works perfectly. Much appreciated. Thanks a lot.
 

My Computer

Computer type
PC/Desktop
OS
windows7 64 bit
Back
Top