string 如何通过在 Windows 中使用批处理替换子字符串来重命名文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16128869/
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-09 01:53:47  来源:igfitidea点击:

How to rename file by replacing substring using batch in Windows

windowsstringfilebatch-filerename

提问by Varun

I want to rename file name like "how-to-rename-file.jpg"to "how-to-reuse-file.jpg"by using a Windows batch file

我想 使用 Windows 批处理文件诸如“how-to- rename-file.jpg”之类的文件名重命名“how-to- reuse-file.jpg”

I.e. I only want to replace one or two words in a file name.

即我只想替换文件名中的一两个词。

回答by ElektroStudios

@echo off

Set "Filename=how-to-rename-file.jpg"
Set "Pattern=rename"
Set "Replace=reuse"

REM Call Rename "%Filename%" "%%Filename:%Pattern%=%Replace%%%"

Call Echo %%Filename:%Pattern%=%Replace%%%
:: Result: how-to-reuse-file.jpg

Pause&Exit

I give you other example for a loop of files:

我给你另一个文件循环的例子:

UPDATE:

更新:

I've missed some things in the syntax 'cause fast-typing my last edit, here is the corrected code:

我在语法中遗漏了一些东西,因为我最后一次编辑的时候打字太快,这里是更正后的代码:

@echo off
Setlocal enabledelayedexpansion

Set "Pattern=rename"
Set "Replace=reuse"

For %%# in ("C:\Folder\*.jpg") Do (
    Set "File=%%~nx#"
    Ren "%%#" "!File:%Pattern%=%Replace%!"
)

Pause&Exit

PS: You can read here to learn more about substring: http://ss64.com/nt/syntax-substring.htmlhttp://ss64.com/nt/syntax-replace.html

PS:您可以在这里阅读以了解有关子字符串的更多信息:http: //ss64.com/nt/syntax-substring.html http://ss64.com/nt/syntax-replace.html

回答by foxidrive

The code above doesn't rename the files - The paths are an issue and the source filename is incorrect.

上面的代码不会重命名文件 - 路径有问题,源文件名不正确。

This will work on files in the current folder - except those with ! in the names will be a problem.

这将适用于当前文件夹中的文件 - 除了那些带有 ! 在名字上会有问题。

@echo off
Setlocal enabledelayedexpansion

Set "Pattern=rename"
Set "Replace=reuse"

For %%a in (*.jpg) Do (
    Set "File=%%~a"
    Ren "%%a" "!File:%Pattern%=%Replace%!"
)

Pause&Exit