Arthur
Arthur

Reputation: 3473

How to rename multiple files in directory?

I have many files in directory with name like

injector.cpython-33.pyo
PregnancyMegaMod.cpython-33.pyo

I need to cut from them .cpython-33 piece, ie after rename files must be like

injector.pyo
PregnancyMegaMod.pyo

How to write Batch File or PowerShell script?

Upvotes: 1

Views: 237

Answers (3)

Magoo
Magoo

Reputation: 80211

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR %%a IN ("%sourcedir%\*.pyo") DO FOR %%b IN ("%%~na") DO IF /i "%%~xb"==".cpython-33" ECHO(REN "%%~fa" %%~nb.pyo"
GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

Obviously, the crux of the method is the for %%a line.

For each file matching the mask in the chosen directory, get the name part, and with that name part, extract the "name" part. If the "extension" part is the expected string, then build the rename command.

Upvotes: 1

dbenham
dbenham

Reputation: 130929

Assuming none of the files have additional dots (in other words, no files like "a.b.cpython-33.pyo"), then you could use something like the following:

ren *.cpython-33.pyo" "??????????????????????????????????????????.pyo"

There must be as many ? as the longest name before .cpython=33.pyo". See How does the Windows RENAME command interpret wildcards? for more info.

If there may be additional dots, then you could use my JREN.BAT utility - a hybrid JScript/batch script that performs rename operations using regular expression replacement. It is pure script that runs natively on any Windows machine from XP onward.

jren "\.cpython-33\.pyo$" ".pyo" /i

Upvotes: 1

Arthur
Arthur

Reputation: 3473

The solution is

Get-ChildItem -Filter "*.pyo" -Recurse | Rename-Item -NewName {$_.name -replace '.cpython-33','' }

Upvotes: 1

Related Questions