我使用以下命令重命名文件并将其移动到目录:
ren credentials* passwords%random%.txt
move E:/passwords*.txt E:/Passwords/
文件重命名会将一个随机数(如1231或类似内容)放入新文件名中 所以我可以分别识别它没有被覆盖的现有文件。但那不是主题。
我想知道的是:我怎样才能进行文件编码?
我希望将当前目录中的credentials*
个文件移至密码目录,其中passwords
X .txt
作为新文件名,根据现有的passwords*.txt
文件,X 应该是下一个免费号码。
因此,如果密码目录中已有passwords1.txt
和passwords2.txt
,则应将文件credentialsX
移至密码目录,并使用新名称passwords3.txt
和{{1 } {} credentialsY
。
答案 0 :(得分:0)
以下是此任务的评论批处理文件,在Stack Overflow上经常询问并经常回答。
@echo off
if not exist "credentials*" goto :EOF
setlocal EnableExtensions DisableDelayedExpansion
set "NextNumber=0"
for %%I in (E:\Passwords\passwords*.txt) do call :GetHighestNumber "%%~nI"
for %%I in (credentials*) do call :MoveFile "%%I"
endlocal
goto :EOF
rem GetHighestNumber is a subroutine which must be called with a passwords*
rem file name without file extension. It determines the number of the current
rem passwords file and compares it with currently highest file number to get
rem finally the currently highest number in all existing passwords*.txt files.
:GetHighestNumber
set "FileName=%~1"
rem Get from file name without file extension the characters after passwords.
set "FileNumber=%FileName:~9%"
rem Ignore the file passwords.txt if existing by chance.
if not defined FileNumber goto :EOF
rem Delete the environment variable FileNumber if it contains any other
rem character than digits to ignore files like passwords12_bak.txt.
for /F "delims=0123456789" %%N in ("%FileNumber%") do set "FileNumber="
rem Has the passwords*.txt file a different string matched by wildcard *
rem than a decimal number, ignore this file and exit this subroutine.
if not defined FileNumber goto :EOF
rem Remove leading zeros to avoid getting the decimal number
rem interpreted as octal number on integer comparison below.
:RemoveLeading0
if not "%FileNumber:~0,1%" == "0" goto CompareNumbers
set "FileNumber=%FileNumber:~1%"
if defined FileNumber goto RemoveLeading0
set "FileNumber=0"
rem The number could be greater than 2147483647 in which case
rem the integer comparison would be not correct because Windows
rem command interpreter does not support larger values.
:CompareNumbers
if %FileNumber% GTR %NextNumber% set "NextNumber=%FileNumber%"
goto :EOF
rem Subroutine MoveFile increases the next file number by 1 and
rem moves the credentials* file to E:\Passwords\passwords*.txt
rem with the incremented file number in file name.
:MoveFile
set /A NextNumber+=1
move %1 "E:\Passwords\passwords%NextNumber%.txt"
goto :EOF
请注意,在Windows上,目录分隔符为\
,而不是Unix / Linux / Mac上的/
。 /
在Windows上通常用作参数的开头,因为它可以在上面的批处理代码中看到,而在Unix / Linux / Mac上-
通常用作参数的开头。
要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。
call /?
echo /?
endlocal /?
for /?
goto /?
if /?
move /?
rem /?
set /?
setlocal /?
另请阅读Where does GOTO :EOF return to?和this answer,了解有关 SETLOCAL 和 ENDLOCAL 命令的详细信息。