简体   繁体   中英

Rename all files and folders in folder and sub folder

I need to rename a whole file structure, and find a certain piece of string such as "_foo" and rename it to "". The structure will be like : something_foo->multiples_folders_and_files_foo->multiples_folders_and_files_foo->files_foo

Where all the files in each folders and each folders in each folders must not contain the piece fo string "_foo".

I am working under windows. I have tried powershell script, I was able to rename a single folder, but not recursivly rename all folders.

thanks guys!

@echo off
setlocal
set "string_to_remove=_foo"
set "root_dir=c:\root"

pushd "%root_dir%"

setlocal enableDelayedExpansion

    for  %%f in (*) do (
        set "file_name=%%f"
        ren "!file_name!" "!file_name:%string_to_remove%=!"

    )


for /r /d %%# in (*) do ( 
    set "dir_name=%%#"
    pushd "%%#"
    for  %%f in (*) do (
        set "file_name=%%f"
        ren "!file_name!" "!file_name:%string_to_remove%=!"

    )
    popd 
    if "!dir_name!" NEQ "!dir_name:%string_to_remove%=!" move  "!dir_name!" "!dir_name:%string_to_remove%=!"
)
popd
endlocal

Not tested but try this (in PowerShell)

PS> ls -rec -path $path |  Ren -new { $_.name -replace '_foo' } -passthru

If work remove - passthru switch

Edit: If '_foo' in the end of the name you can change the expression like:

|  Ren -new { $_.basename -replace '_foo$' } -ea silentlycontinue

Edit:

For more robust code: (thank TheMadTechnician)

PS> GCI $path -filter '*_foo*' -rec |  Ren -new { $_.name -replace '_foo' } -passthru
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "remove=_foo"

    for /f "delims=" %%a in ('dir /s /b "*%remove%*.*" 2^>nul ^| sort /r') do (
        set "name=%%~nxa"
        setlocal enabledelayedexpansion
        for %%b in ("!name:%remove%=!") do endlocal & echo ren "%%~fa" "%%~b"
    )

This will enumerate all matching files/folders, sort in reverse order (so files are processed before the folders that contains them) and for each one, remove the indicated string

Rename operations are only echoed to console. If the output is correct, remove the echo command

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