开发者

Rename files using batch [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_JS百科 Closed 10 years ago.

I have a folder with files x_blah.blah y_ho.hum z_hi.ho which I just need to drop everything to left of the underscore and the underscore from so I'm left with blah.blah ho.hum hi.ho


This should do the trick:

setlocal enabledelayedexpansion

for %%i in (*_*) do (
   set old_name=%%i
   set new_name=!old_name:*_=!
   move "!old_name!" "!new_name!"
)

For explanation:

  • setlocal enabledelayedexpansion enables the so called delayed variable expansion, a feature that e.g. allows you to dereference variables inside loops
  • for %%i in (*_*) do starts a loop over all file names inside the current directory that at least have one _ and assigns that file name to the loop variable %%i
  • set old_name=%%i assigns the content of the loop variable to a regular variable named old_name
  • set new_name=!old_name:*_=! does some nice string substitution on the content of the variable old_name, replacing all characters before the first _ and the _ itself with nothing. The result is stored in new_name. See the help of the SET command for more details (type help set on the command line).
  • move "!old_name!" "!new_name!" finally is the command issued to rename each file from its old to its new name

Update:

To go through the files in all sub folders you can use the FOR /R variation of the for loop. To start in the current directory, change the loop header to something like:

for /r %%i in (*_*) do (

But you also need to take into account that the loop variable now contains the fully qualified path of the file name, so you also have to change the loop body a bit to only substitute the file name:

for /r %%i in (*_*) do (
   set file_path=%%~dpi
   set old_file_name=%%~nxi
   set new_file_name=!old_file_name:*_=!
   move "!file_path!!old_file_name!" "!file_path!!new_file_name!"
)

Hope that helps.


Windows Batch

@echo off

FOR %%i in (PREFIX*.txt) DO (set file=%%i) & CALL :rename
GOTO :eof

:rename
REN "%file%" "%file:~6%"
GOTO :eof

You need to adjust the 6 to the length of the prefix. So for your example, you could do this:

@echo off

FOR %%i in (x_*.txt) DO (set file=%%i) & CALL :rename
GOTO :eof

:rename
REN "%file%" "%file:~2%"
GOTO :eof

Linux

Linux has multiple solutions, one of them would be this:

rename 's/^x_//' *

where x_ is the prefix.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜