从 windows 中我的文件名中删除最后一个字符

Remove Last Characters from my filenames in windows

我对批处理编程还很陌生,我想删除文件名中的最后一个字符。

10_myfile_12345_6789.txt
11_myfile_12345_0987.txt

我想删除文件名的最后 4 位数字,我该怎么做?

我试过了

@echo off
setlocal enabledelayedexpansion
set X=3
set FOLDER_PATH=
pushd %FOLDER_PATH%
for %%f in (*) do if %%f neq %~nx0 (
    set "filename=%%~nf"
    ren "%%f" "!filename!%%~xf"
)
popd
PAUSE

但是它删除了第一个和最后一个字符,我也只在这里看到这个,我仍然很困惑它是如何工作的

根据您最近的说明 - 我将执行以下操作。

@echo off
setlocal enabledelayedexpansion
set FOLDER_PATH=C:\Some\Path\
for %%f in (%FOLDER_PATH%*) do if %%f neq %~nx0 (
    set "filename=%%~nf"
    ren "%%f" "!filename:~0,-4!%%~xf"
)
PAUSE

这将改变您的示例

10_myfile_12345_6789.txt
11_myfile_12345_0987.txt

进入

10_myfile_12345_.txt
11_myfile_12345_.txt

如果要删除尾随 _,只需将 !filename:~0,-4! 更改为 !filename:~0,-5!。这很简单 string manipulation.

::working script to rename + remove suffix
::fixed problem file is not found while rename.
@echo off
set /a count = 0
for %%i in ("*.ts") do (set fname=%%i) & call :rename
goto :eof
:rename
::template name ==>   names__1xxx.ts
::to rename the begin  change zero to something
set name=%fname:~0,-8%
set /a count=count+1
::by random or count i bypass the problem of file not found while rename
ren "%fname%" "%name%_%count%.ts`

结果:

之前:names__1xxx.ts

之后:names__1.ts