Search code examples
powershellbatch-filebatch-rename

How To Remove Substring Using Batch File


I have several thousand files with similar, but different formats, ie:

[Block 1] Thisfile.txt
[Block 1] Thisfile1.txt
[Block 1] Thisfile2.txt
[Backup001] Thatfile1.doc
[Backup001] Thatfile2.doc
[Backup001] Thatfile3.doc
[Explode] Thisplace.xls
[Explode] Thisplace1.xls
[Explode] Thisplace2.xls

I want to remove the "[text] " and keep everything else the same. Since that text varies I can't do a strict number of characters ie

set var=%1
@echo %var:~-7%

I tried to dabble with powershell commandline and tried:

dir *.xls | Rename-Item -NewName {$_.Name -replace '[Explode\s\'}

But was given the following error:

Rename-Item : The input to the script block for parameter 'NewName' failed. Invalid regular expression pattern: [Explode\s\.
At line:1 char:33
+ Dir *.xls | Rename-Item -NewName <<<<  {$_.Name -replace '[Explode]\s\'}
    + CategoryInfo          : InvalidArgument: (C:\1\[Explode... Thisfile1.xls:PSObject) [Rename-Item], ParameterBindingException
    + FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.RenameItemCommand

I've searched StackExchange, and the 'batch-rename' tag, and found (and tried) several similar things that I thought I could tweak, but no luck.

Here's the latest based on another StachExchange answer:

for %%F in (*.xls) do (
    SET string=%%F
    SET modified=!string:Explode=1!
    echo !modified!
)

I was just trying to get ANY replace to work... No luck.


Solution

  • Using pure batch:

    @echo off
    for /f "delims=" %%F in (
      'dir /b /a-d [*]*'
    ) do for /f "tokens=1* delims=]" %%A in (
      "%%F"
    ) do for /f "tokens=*" %%C in ("%%B") do ren "%%F" "%%C"
    

    Using my JREN.BAT regular expression renaming utility, a pure script utility (hybrid JScript/batch) that runs natively on any Windows machine from XP onward:

    call jren "^\[.*?] *" "" /fm "[*]*"
    

    You can drop the CALL if you use the command directly from the command line.