从Windows文件名中删除最后几个字符

3

我对批处理编程还是很新的,我想要删除文件名中的最后几个字符。

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

但它会移除第一个和最后一个字符,我也只在这里看到过这种情况,我还是很困惑这是如何工作的。


我已经编辑了我的帖子,我正在DOS上运行它。 - Xander Vane
1
有许多实用工具,例如RenameMaster,可以完成此任务。为什么您不能使用其中之一呢? - Dour High Arch
我不能在我的笔记本电脑上安装任何东西,即使是免费软件,因为存在安全风险。 - Xander Vane
@XanderVane 请看我的回答。 - unclemeat
那个RenameMaster太棒了!它从630个文件名中删除了最后一个字符,为我节省了大量时间。我甚至不需要安装任何东西。它只是一个带有可执行文件的ZIP文件。 - CaptainGenesisX
显示剩余3条评论
3个回答

8

根据您最近的澄清 - 我会采取以下措施。

@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

Into

10_myfile_12345_.txt
11_myfile_12345_.txt

如果你想要去掉末尾的_,只需将!filename:~0,-4!更改为!filename:~0,-5!。这是简单的字符串操作

谢谢您提供的信息,但似乎目录名称已更改。 - Xander Vane
@XanderVane 我其实没有测试我的解决方案 - 我的错。请查看更新版本。在for循环中添加了*以获取目录的内容,而不是目录本身。 - unclemeat

0
非常感谢DIMM_V2,文件现在如下所示:
::working script to rename + remove suffix
::fixed problem file is not found while rename.
@echo off
set /a count = 0
for %%i in ("*_removed.PDF") do (set fname=%%i) & call :rename
goto :eof
:rename
::template name ==> name_removed.PDF
::to rename the begin  change zero to something
set name=%fname:~0,-12%
set /a count=count+1
::by random or count i bypass the problem of file not found while rename
ren "%fname%" "%name%.PDF"

这个完美地起作用了。文件被重命名得正如我所愿。只需简单地选中文件,按下F2键,然后重命名它,虽然很简单,但是由于我经常需要这样做,所以有点烦人。这个批处理文件让我的生活变得轻松得多!再次感谢!

0
::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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接