简体   繁体   中英

Rename file name while removing part of file name

i have a folder and it contains hundreds of text file, i want to rename it .

file names ABCD01%%.txt or CAT9999&#.txt OR FILENAME2345&^$.txt

i want to rename file such that anything that comes between 'numbers' and '.txt' should be removed

for example

  • ABCD01%%.txt becomes ABCD01.txt

  • CAT9999&#.txt becomes CAT9999.txt

  • FILENAME2345&^$.txt becomes FILENAME2345.txt

Code so far:

@echo off
for /f "tokens=*" %%f in ('dir /l /a-d /b *.txt') do (
    for /f "tokens=1 delims=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" %%n in ("%%~nf") do (
        echo File: %%~nxf = value %%n

    rename %%~nxf *%%n.txt



    )
)

Another solution i get for linux is rename 's/[^a-zA-Z0-9_]//g' *.txt , i tried to port it for windows but i cant .. how can the above command be ported to windows (batch)

I've encountered a few problems with escaping characters, I had to use a slightly different method. This script should work:

setlocal enabledelayedexpansion
for %%f in (*.txt) do (
    set name=%%~nf
    for /f "delims=0123456789 tokens=2" %%r in ("%%~nf") do set replace=%%r
    set "replace=name:!replace:^^=!="
    for /f %%x in ("!replace!") do set replace=!%%x!
    ren "!name!.txt" "!replace!.txt"
)

EDIT: This revised script looks for the last numbers in the file name. [ Don't mind the errors, they don't have any effect on the actual renaming. ]

setlocal enabledelayedexpansion
for %%f in (*.txt) do (
    set name=%%~nf
    set p=0
    for /l %%# in (2 1 32) do (
        for %%e in ("!name:~-%%#,1!") do (
            echo.%%~e|findstr /r /i "[0-9]"&&if !p!==0 set /a p=%%#-1
        )
    )
    set "new=name:~,-!p!"
    for %%e in ("!name:~-1!") do echo.%%~e|findstr /r /i "^[0-9]"&&set new=name
    for /f %%x in ("!new!") do ren "!name!.txt" "!%%~x!.txt"
)

EDIT: Revised again for the special case of "&&". Delayed expansion within a for-loop can be tedious. Now the characters won't break syntax anymore (which means the errors that were to be ignored have ceased).

Assuming there are no duplicate renames and assuming that only letters and numbers make up the first part of the filename, the following code will rename the files. When you are satisfied that the renaming is being done correctly, remove the -WhatIf from the Rename-Item command.

Get-ChildItem -File -Filter '*.txt' |
    Where-Object { $_.Name -match '([A-Za-z0-9]*).*\.txt' } |
    ForEach-Object { Rename-Item $_.FullName "$($matches[1]).txt" -WhatIf }

If you are not running in PowerShell, put the code into a renfunc.ps1 file and invoke it from the cmd .bat script.

powershell -NoProfile -File 'renfunc.ps1'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM