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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27931611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:53:50  来源:igfitidea点击:

Remove Last Characters from my filenames in windows

windowsbatch-filefilenamesrename

提问by Xander Vane

Im quite new to batch programming and i wanted to remove the last characters on my filename.

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

10_myfile_12345_6789.txt
11_myfile_12345_0987.txt

I want to remove the last 4 digits on my filename how i could do that?

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

I have tried this

我试过这个

@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

but it removes on first and last characters, i only saw this here too, im still quite confused how this works

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

回答by unclemeat

With your recent clarification - I would do the following.

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

@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

This will change your examples

这将改变你的例子

10_myfile_12345_6789.txt
11_myfile_12345_0987.txt

Into

进入

10_myfile_12345_.txt
11_myfile_12345_.txt

If you want to remove the trailing _simply change !filename:~0,-4!to !filename:~0,-5!. This is simple string manipulation.

如果您想删除尾随,_只需更改!filename:~0,-4!!filename:~0,-5!. 这是简单的字符串操作