简体   繁体   English

Windows重命名文件的批处理脚本

[英]windows batch script for renaming files

I have a lot of files in a windows folder. 我在Windows文件夹中有很多文件。 These file names contain a lot of underscores as well. 这些文件名也包含很多下划线。 Eg: 例如:

 ad_iod_errr_opp12.txt ghff_jjk56.txt opr_sdr_ot_wrr_12ee.txt 

I want to rename these files such that the last underscore and everything following it is removed and the files are renamed as follows: 我想重命名这些文件,以便删除最后一个下划线及其后面的所有内容,并按以下方式重命名文件:

 ad_iod_errr.txt ghff.txt opr_sdr_ot_wrr.txt 

Note: The number of underscores varies. 注意:下划线的数量有所不同。 Some filenames may have just a single underscore, whereas other filenames may have up to 8 underscores. 某些文件名可能只有一个下划线,而其他文件名可能最多有8个下划线。 I am looking for a Windows batch script which could do the trick and not PowerShell commands. 我正在寻找可以解决问题的Windows批处理脚本,而不是PowerShell命令。

This is the code that I am using currently to rename the files considering that the file names have only one underscore in it: 考虑到文件名中只有一个下划线,这是我当前正在使用的代码来重命名文件:

@ECHO OFF 
SETLOCAL 
cd C:\Users\ambika.narayan.rao\JenkinsWorkspace 
SET "fname=*.txt" 
FOR %%i IN ("%fname%") DO FOR /f "delims=_" %%j IN ("%%i") DO ren "%%~i" "%%~j%%~xi" 
GOTO :EOF
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%sourcedir%\*_*.txt" '
 ) DO (
 SET "filename=%%a"
 set "partsname=!filename:_= _!"
 FOR %%b IN (!partsname!) DO SET "newname=!filename:%%b=!%%~xa"
 ECHO REN "%sourcedir%\%%a" "!newname!"
)

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances. 您需要更改sourcedir的设置以适合您的情况。

The required REN commands are merely ECHO ed for testing purposes. 所需REN命令仅仅ECHO编用于测试目的。 After you've verified that the commands are correct , change ECHO(REN to REN to actually rename the files. 验证命令正确无误后 ,将ECHO(REN更改为REN即可实际重命名文件。

Perform a directory scan of all filenames matching the mask. 对与掩码匹配的所有文件名执行目录扫描。 WIth each name found, using delayed expansion, assign the name to filename and then replace each _ with Space _ 找到的每个名称都使用延迟扩展,将名称分配给filename ,然后将每个_替换为空格 _

Use a simple for to assign newname to the original filename with the _string removed (replaced by nothing ) and add back the extension using %%~xa . 使用简单的for来将newname分配给_string删除_string的原始文件名(不替换任何内容 ),然后使用%%~xa _string重新添加扩展名。 The last string assigned to %%b will be _laststring.ext , so the value assigned to newname will fit the processing requirement, so rename the file. 分配给%%b的最后一个字符串将是_laststring.ext ,因此分配给newname的值将满足处理要求,因此重命名该文件。

Here is a modified script that I posted in another answer , relying on a nice hack to remove the last portion of a string separated by a certain character – the underscore _ in this case. 这是一个修改后的脚本,我在另一个答案中发布了该脚本,该脚本依靠一个不错的技巧删除由某个字符分隔的字符串的最后部分-在这种情况下为下划线_ Note that this fails in case any of the files contains exclamation marks ! 请注意,如果任何文件包含感叹号,此操作将失败! in their names. 以他们的名字。 So this is the code: 所以这是代码:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_SOURCE=%~dp0."
set "_MASK=*_*.txt"

rem // Enumerate all matching files:
for /F "delims= eol=|" %%F in ('dir /B /A:-D "%_SOURCE%\%_MASK%"') do (
    rem // Store current file name and extension:
    set "FILE=%%~nF" & set "FEXT=%%~xF"
    rem // Call sub-routine that removes the last `_`-separated part:
    call :GET_LAST_ITEM LAST RMND "%%~nF"
    rem // Enable delayed expansion to be able to read the variables:
    setlocal EnableDelayedExpansion
    rem /* Actually rename current file: */
    ECHO ren "!FILE!!FEXT!" "!RMND!!FEXT!"
    endlocal
)

endlocal
exit /B


:GET_LAST_ITEM  rtn_last  rtn_without_last  val_string
    ::This function splits off the last `_`-separated item of a string.
    ::Note that exclamation marks must not occur within the given string.
    ::PARAMETERS:
    ::  rtn_last            variable to receive the last item
    ::  rtn_without_last    variable to receive the remaining string
    ::  val_string          original string
    setlocal EnableDelayedExpansion
    set "STR=_%~3"
    set "PRE=" & set "END=%STR:_=" & set "PRE=!PRE!_!END!" & set "END=%"
    endlocal & set "%~1=%END%" & set "%~2=%PRE:~2%"
    exit /B

To be able to also handle file names with exclamation marks correctly, here is a different approach: 为了也能够正确处理带有感叹号的文件名,这是另一种方法:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_SOURCE=%~dp0."
set "_MASK=*_*.txt"

rem // Enumerate all matching files:
for /F "delims= eol=|" %%F in ('dir /B /A:-D "%_SOURCE%\%_MASK%"') do (
    rem // Store current file name and extension:
    set "FILE=%%~nF" & set "FEXT=%%~xF"
    rem // Initialise some variables:
    set "NAME=" & set "ITEM="
    rem // Toggle delayed expansion to not lose `!` in file names:
    setlocal EnableDelayedExpansion
    rem /* Loop through all partial file names separated by `_`; since every
    rem    `_` is replaced by `" "` and the whole string is enclosed in `""`,
    rem    we effectively get a list of quoted file name parts, which were
    rem    originally separated from each other by `_`: */
    for %%I in ("!FILE:_=" "!") do (
        rem /* Rebuild file name but delayed by one name part; the `for /F` loop
        rem    iterates once and transports the result beyond `endlocal`: */
        for /F "delims= eol=|" %%E in ("!NAME!!ITEM!_") do (
            endlocal
            set "NAME=%%E"
        )
        rem // Belatedly store currently iterated file name part:
        set "ITEM=%%~I"
        setlocal EnableDelayedExpansion
    )
    rem /* Actually rename current file; superfluous leading and trailing `_`
    rem    are removed from the rebuilt file name: */
    ECHO ren "!FILE!!FEXT!" "!NAME:~1,-1!!FEXT!"
    endlocal
)

endlocal
exit /B

After having successfully tested the scripts, remove the upper-case ECHO commands to actually rename any files! 成功测试脚本后,请删除大写的ECHO命令以实际重命名任何文件!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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