如何重命名文件,删除第一个下划线和后4个字符之间的文件名中的所有字符?

时间:2016-06-29 16:33:32

标签: batch-file

我试图从文件名的第一个下划线和后四个字符之间删除文件名中的所有字符并保留文件扩展名。

因此,例如crashmaster_01011990_12311990.txt将成为crashmaster_1990.txt

我不能只对前12个字符进行硬编码,因为还有其他文件,例如crashcarrier_01011990_12311990.txt会将其丢弃。

以下代码不起作用,但即使如此,我也不想删除最后18个字符。而是保存最后4个并附加在第一个下划线之后。

for %%i in (*.txt) do (
    set fName=%%i
    ren "%fName%" "%fName:~-18%.txt" 
)
pause

1 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案,其中包含额外的代码,这些代码很可能不是真正需要验证要重命名的文件的名称。

通过使用子程序,此代码可以避免在使用@Entity @Table(name="EMPLOYEE") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Size(min=3, max=50) @Column(name = "NAME", nullable = false) private String name; //.. } ... (定义的命令块中使用延迟环境变量扩展的要求。

)

在真正重命名文件之前进行测试要么用命令@echo off setlocal EnableExtensions for %%I in (*_*.txt) do call :FileRename "%%~nxI" endlocal goto :EOF rem This subroutine interprets name of a file being valid for rename rem under following conditions: rem 1. File name does not start with an underscore. rem 2. File name does not end with an underscore. rem 3. There are at least 4 characters after first underscore in name. rem 4. A file with the new file name does not already exist. rem The last condition is necessary to avoid rem 1. renaming a file with longer name to an already existing file rem because that would result in an error message on rename and rem 2. renaming a file which was already renamed before and because rem of that the new file name is equal the current file name. :FileRename set "FileName=%~n1" if "%FileName:~0,1%" == "_" goto :EOF if "%FileName:~-1%" == "_" goto :EOF for /F "tokens=1* delims=_" %%A in ("%FileName%") do ( set "NamePartFirst=%%A" set "NamePartRest=%%B" ) if "%NamePartRest:~3,1%" == "" goto :EOF set "NewFileName=%NamePartFirst%_%NamePartRest:~-4%%~x1" if not exist "%NewFileName%" ren "%~nx1" "%NewFileName%" goto :EOF 替换命令ren,要么在最后一行中将命令echo留给echo

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • ren
  • call /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • ren /?
  • set /?