How to delete first 7 characters of folder name by

2019-06-08 04:04发布

I did do research but I could not figure out, sorry! Google can only help me to add characters but not delete characters...

say under the dir E:\Movies\2011\

there are several folders e.g.

[0603] Movie_1

[0708] Movie_2

[0811] Movie_3

and so on..

So I want to run a batch script to remove date tag i.e.

Movie_1

Movie_2

Movie_3

and so on

I am using windows 8.

3条回答
做个烂人
2楼-- · 2019-06-08 04:12

RENAMER.CMD

@echo off
setlocal enableextensions enabledelayedexpansion
for %%i in (*) do (set name=%%i && ren "!name!" "!name:~7!")
endlocal

Explanation:

The setlocal / endlocal stuff just makes sure that the script will work no matter what your default commandline settings are. Those lines are optional if you make sure that command extensions and delayed expansion are enabled by default, or if you start your command prompt using cmd /e:on /v:on.

The for statement is the heart of the thing. It selects every file in the directory using (*). If you only want to change files with certain extensions you can use a different pattern such as (*.avi). Then !name:~7! takes seven characters off the front. set /? lists some of the other manipulations you can perform. Most of the examples use % instead of ! but all string manipulations work with both.

Updated to answer comment

You can perform a % substitution inside a ! substitution.

@echo off
setlocal enableextensions enabledelayedexpansion
set numtrim=7
for %%i in (*) do (set name=%%i && ren "!name!" "!name:~%numtrim%!")
endlocal
查看更多
Rolldiameter
3楼-- · 2019-06-08 04:27

Since you are using Win8, you can use powershell to also accomplish this. Here is what I used to turn

blah11-1 blah12-1 blah13-1

to

blah11 blah12 blah13

C:\testing> dir -Directory | foreach { if($.Name.Length -gt 6){ $fileName = $.Name.SubString(0,6)} else { $fileName = $.Name }; rename-item -path $.fullname -newname $fileName; }

Now this is just what I ran on the powershell command line, but it could be moved into a script to make it more reusable.

查看更多
祖国的老花朵
4楼-- · 2019-06-08 04:29

You can use the enhanced variable substitution features to do this (SET /? for information):

@echo off
setlocal
for /d %%i in (*) do call :rename %%i
goto :eof
:rename
set CURDIR=%1
echo ren "%CURDIR%" "%CURDIR:~7%"

The magic happens at %CURDIR:~7%, which means "the value of %CURDIR%, but skip the first 7 characters".

The batch file above does not rename anything (it just prints the rename command), so you can do a dry run first and then remove the final echo to get the real job done.

查看更多
登录 后发表回答