[英]Creating a batch file to modify the filenames in a directory
Im trying to build a batch file. 我试图建立一个批处理文件。
I have 30 csv files in a folder 我在一个文件夹中有30个csv文件
My intention is 我的意图是
EG: lookup1.bat
EG:lookup1.bat
@echo 107=B_05-
@echo 097=B_06-
@echo 149=B_07-
@echo 109=B_08-
@echo 101=B_09-
@echo 105=B_10-
@echo 098=B_11-
So here i will get "B_06-" 所以在这里我会得到“B_06-”
Here is my code , i have only basic ideas about looping and im struggling a lot.Thanks for any help. 这是我的代码,我只有关于循环的基本想法和我很多努力。感谢任何帮助。
@echo on
setlocal enabledelayedexpansion
for %%a in ("*.csv") do (
set FileName=%%~na
goto:stepa
goto:eof
)
:stepa
for /f "tokens=1 delims=_" %%a in ("%FileName%") do (
set A=%%a
echo %A%
)
@SET MN=%A%
@FOR /F "tokens=1,2 delims==" %%i IN ('lookup1.bat') DO @IF %%i EQU %MN% SET MW=%%j
@ECHO The board number corresponding to %MN% is %MW%.
set "str=%MW%%FileName%"
echo "%str%"
Ren "!FileName!" "!str!"
:eof
You have a series of problems with the structure of your program. 您的程序结构存在一系列问题。 If you want to call a subroutine from inside a
for
command the right way is using call
, not goto
, and the goto :eof
command must be placed after the for
ends. 如果你想从里面调用子程序
for
命令以正确的方式是使用call
,而不是goto
和goto :eof
命令必须放置后 for
末端。 However, this code is simple enough so it don't requires a subroutine. 但是,这段代码很简单,因此不需要子程序。
The table lookup method is more efficient (and also simpler, IMHO) if you use an array to load the table just once, and then directly access its elements via an index . 如果您使用数组只加载一次表,然后通过索引直接访问其元素,则表查找方法更有效(也更简单,恕我直言)。
@echo off
setlocal EnableDelayedExpansion
rem Create the lookup file with lookup1.bat file,
rem this program create lines like this one:
rem 097=B_06-
call lookup1.bat > lookup1.txt
rem Load the lookup table from the file,
rem this method create _array elements_ like this one:
rem set "table[097]=B_06-"
for /F "tokens=1,2 delims==" %%a in (lookup1.txt) do set "table[%%a]=%%b"
rem Process the files in current folder,
rem file name format is this:
rem ###_restOfFileName.csv
for /F "tokens=1* delims=_" %%a in ('dir /A:-D /B *.csv') do (
@ECHO The board number corresponding to %%a is !table[%%a]!.
ren "%%a_%%b" "!table[%%a]!%%b"
)
You may test if the board number is not defined for a file via an additional if not defined table[%%a] ...
command placed inside the for
. 您可以通过放置在
for
的附加if not defined table[%%a] ...
命令来测试是否未为文件定义板号。
You may directly create the lookup1.txt
file with your text editor; 您可以使用文本编辑器直接创建
lookup1.txt
文件; just eliminate all these @echo
parts from lookup1.bat
and change the extension. 从
lookup1.bat
删除所有这些@echo
部分并更改扩展名。
You may review a detailed explanation on array use in Batch files at this answer . 您可以在此答案中查看有关批处理文件中阵列使用的详细说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.