批处理文件,用.txt文件中的文本检查输入的文本

时间:2022-04-25 02:22:40

I like to have a batch file which checks if an entered text in a .txt file is the same.

我想要一个批处理文件来检查.txt文件中输入的文本是否相同。

Something like this:

像这样的东西:

@echo off
Set pass=
set /p pass=Enter your password:
......
......

The .txt file is pass.txt, and it should look something like this:

.txt文件是pass.txt,它看起来像这样:

p2342ddd3

So what I want it to do, that an user have to type in the text from the pass.txt file (not looking at it obviously) and that the batch file checks if it is similar with the text from the pass.txt file.

所以我想要它做的是,用户必须输入pass.txt文件中的文本(显然不看它),批处理文件检查它是否与pass.txt文件中的文本相似。

2 个解决方案

#1


This will require a combination of a for loop and simple if:

如果出现以下情况,则需要组合使用for循环和简单:

@echo off
:begin
set pass=
set /p pass=Enter your password: 
if {%pass%}=={} goto :begin
set authenticated=
for /f "tokens=*" %%a in (pass.txt) do (
    if {%%a}=={%pass%} set authenticated=true
)

if not defined authenticated (echo Invalid password & goto :begin)
exit /b 0

#2


You can use the built-in command FINDSTR to match the password in the password file:

您可以使用内置命令FINDSTR来匹配密码文件中的密码:

@echo off
set pass=
set /p pass=Enter your password:

findstr /B /E /M %pass% pass.txt > nul
If %ERRORLEVEL% EQU 0 echo Password matched!

Options /B and /E are for ensuring that the whole password is matched and no partial matching takes place. E.g. 42 is contained in p2342ddd3, but should not result in a match.

选项/ B和/ E用于确保匹配整个密码并且不进行部分匹配。例如。 42包含在p2342ddd3中,但不应导致匹配。

Options /M and the redirection to nul is to ensure the password does not leak out.

选项/ M和重定向到nul是为了确保密码不会泄漏。

FINDSTR sets variable ERRORLEVEL to 0 if an item is found (password match) and to a value greater than 0 if an item is not found.

如果找到一个项目(密码匹配),FINDSTR将变量ERRORLEVEL设置为0,如果找不到项目,则将变量设置为大于0的值。

#1


This will require a combination of a for loop and simple if:

如果出现以下情况,则需要组合使用for循环和简单:

@echo off
:begin
set pass=
set /p pass=Enter your password: 
if {%pass%}=={} goto :begin
set authenticated=
for /f "tokens=*" %%a in (pass.txt) do (
    if {%%a}=={%pass%} set authenticated=true
)

if not defined authenticated (echo Invalid password & goto :begin)
exit /b 0

#2


You can use the built-in command FINDSTR to match the password in the password file:

您可以使用内置命令FINDSTR来匹配密码文件中的密码:

@echo off
set pass=
set /p pass=Enter your password:

findstr /B /E /M %pass% pass.txt > nul
If %ERRORLEVEL% EQU 0 echo Password matched!

Options /B and /E are for ensuring that the whole password is matched and no partial matching takes place. E.g. 42 is contained in p2342ddd3, but should not result in a match.

选项/ B和/ E用于确保匹配整个密码并且不进行部分匹配。例如。 42包含在p2342ddd3中,但不应导致匹配。

Options /M and the redirection to nul is to ensure the password does not leak out.

选项/ M和重定向到nul是为了确保密码不会泄漏。

FINDSTR sets variable ERRORLEVEL to 0 if an item is found (password match) and to a value greater than 0 if an item is not found.

如果找到一个项目(密码匹配),FINDSTR将变量ERRORLEVEL设置为0,如果找不到项目,则将变量设置为大于0的值。