1

如果文件名末尾不包含特定字符串,我正在尝试编写一个重命名文件名的批处理文件。例如,我有一个包含以下文件的文件夹:

测试文件 1.csv
测试文件 2 Zac.csv

对于末尾(扩展名之前)不包含“Zac”(不带引号)的每个文件,我想在文件名中添加“Zac”。所以结果是:

测试文件 1 Zac.csv
测试文件 2 Zac.csv

这是我目前拥有的批处理文件:

for %%f in (*.csv) do (ren "%%f" ???????????????????????????????" Zac.csv"

但这会将“Zac”添加到所有文件中,即使它们已经包含“Zac”。如何仅更改末尾没有“Zac”的文件?

非常感谢!

4

3 回答 3

3
    for /f "delims=" %%a in ('dir /b /a-d *.csv ^|findstr /iv "zac"') do echo ren "%%~a" "%%~na Zac%%~xa"

查看输出并删除echo它是否看起来不错。
注意:如果文件存在已经ren失败并且您收到错误消息。

于 2013-09-26T21:36:40.233 回答
0

这应该有效:

@echo off
: create variable to track number of files renamed
set filesRenamed=0
: loop through csv files and call Rename routine
for %%f in (*.csv) do call :Rename "%%f" filesRenamed
: output results
echo %filesRenamed% files renamed
: clear variables
set filesRenamed=
set tmpVar=
: Goto end of file so we don't call rename an extra time
goto :eof

:Rename
: need a local environment variable with filename for manipulation
set tmpVar=%1
: remove the closing quotes
set tmpVar=%tmpVar:~0,-1%
: compare the last 8 characters and rename as necessary
if /I NOT "%tmpVar:~-8%" EQU " Zac.csv" (
    : use original file name parameter which is already quoted
    ren %1 ???????????????????????????????" Zac.csv"
    : increment the renamed file count
    set /A %2=%2+1
)

有关批处理文件中子字符串处理的详细描述,请参阅此其他帖子。

于 2013-09-26T22:03:36.127 回答
0

使用renamer,这些输入文件:

Test File1 Zac.csv
Test File2.csv
Test File3.csv
Test File4.xls
Test File5 Zac.csv

使用此命令:

$ renamer --regex --find '(Test File\d)(\.\w+)' --replace '$1 Zac$2'  *

导致这些新文件名:

Test File1 Zac.csv
Test File2 Zac.csv
Test File3 Zac.csv
Test File4 Zac.xls
Test File5 Zac.csv

如果您需要更多帮助,请告诉我。

于 2013-09-27T09:18:15.683 回答