How to use “ren” or “rename” to truncate the file name until underscored?

。_饼干妹妹 提交于 2020-05-17 06:00:55

问题


I have some file names as below saved in C:\aaa\temp

Before:

92485345_A0027777882244.zip
87493354_A0027684085444.zip
87111901_A0027871905777.zip

some fixed rule in the file name:

  1. I need to delete the characters until the underscore "_"
  2. The name after underscore always begins with A0027

Can someone please teach me how to write a script to batch rename them as below:

After:

A0027777882244.zip
A0027684085444.zip
A0027871905777.zip

回答1:


If the number of characters in front of the underscore _ is always the same, then use this:

rem // Expecting 8 characters in front of `_`:
ren "????????_A0027*.zip" "/////////*.*"

This is an undocumented feature of ren, which is described there.


When the number of characters in front of _ can vary you have to use dir /B to get the list of matching files, a for /F loop to capture it and to split the file names, then ren to finally rename each file:

for /F "tokens=1* delims=_" %E in ('dir /B /A:-D "*_A0027*.zip"') do @ren "%E_%F" "%F"

To use this code in a batch-file you need to change % to %%:

for /F "tokens=1* delims=_" %%E in ('dir /B /A:-D "*_A0027*.zip"') do (
    ren "%%E_%%F" "%%F"
)



回答2:


  • List the files from the directory.
  • Iterate through the list of names.
  • Remove chars up until the underscore (including).
  • Rename each file to the new name as you iterate through list.

Now, if you chose to do this with a script or pipe through, it is up to you.



来源:https://stackoverflow.com/questions/58543907/how-to-use-ren-or-rename-to-truncate-the-file-name-until-underscored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!