Question

I'm working on a Windows batch file and I need to change name of files in current direcotry.

I have these files:

file1.txt
file2.txt
file3.txt

and I need to add string "REG~" before each filename like this

REG~file1.txt
REG~file2.txt
REG~file3.txt

Thank you.

Was it helpful?

Solution 2

@echo off    
SETLOCAL ENABLEDELAYEDEXPANSION    
SET old=file  
SET new=REG~file   
for /f "tokens=*" %%f in ('dir /b *.txt') do (    
    SET newname=%%f    
    SET newname=!newname:%old%=%new%!    
move "%%f" "!newname!"    
)

What this does is it loops over all .txt files in the folder where the batch file is located and replaces the file with December inside the filenames.

OTHER TIPS

Run this in a folder with .txt files in it. Use test files first.

@echo off
for %%a in (*.txt) do ren "%%a" "REG~%%a.tmp"
ren *.tmp *.

For anyone who stumbles on to this, just one tweak to this code - add "txt" (or the appropriate file extension) to the very end:

@echo off
for %%a in (*.txt) do ren "%%a" "REG~%%a.tmp"
ren *.tmp *.txt

If your are using windows, this work for me.

If you want to add any prefix to file names, it can be done as in the below example. Here we try to add ‘photo’ to every txt file in the current folder and subfolders.

forfiles /S /M *.txt /C "cmd /c rename @file photo@file"

Source: https://www.windows-commandline.com/rename-file-extensions-bulk/

If you want to use Powershell, the following in a .bat would do too (and more powerful.):

powershell.exe -command "get-childitem *.txt | rename-item -newname { 'REG~' + $_.Name }"

use this in command prompt

for /f "delims=" %a in ('dir /b /a-d *.txt') do ren "%a" "REG~%a"

or for batch file/scheduler change the %a to %%a

for /f "delims=" %%a in ('dir /b /a-d *.txt') do ren "%%a" "REG~%%a"

it use for loop and wildcard file with txt extension *.txt

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top