-2

I'm fairly new to CMD but I keep experimenting and searching a lot about it and I've came to a dead-end. So my question is this: Is is possible for a batch file to read a certain line from a .txt file, and then compare it to some user input? In essence, what I want to create is to have a standart .txt file (which will be holding some information) and a batch file which, once initiated, will be asking the user for some information, and then compare that with a specific .txt file line to see wether the user input matches the info in the .txt. So far, the comparison is what I cannot code. Any help? Thanks. ;)

iNT
  • 3
  • 1
  • 4
    Have you even tried to google for it? Go step by step with searching... http://stackoverflow.com/questions/14834625/reading-text-file-in-batch-script ... http://stackoverflow.com/questions/1223721/in-windows-cmd-how-do-i-prompt-for-user-input-and-use-the-result-in-another-com – Marek Bernád Mar 06 '17 at 22:14

2 Answers2

0

You can read the textfile into a variable using SET. For example, place a file data.txt on the desktop containing the word password. Then put this in your batch file:

@echo off
SET /p txt=<%userprofile%\Desktop\data.txt

IF "%1" == "%txt%" (
    ECHO "%1 matched!"
) ELSE (
    ECHO "%1 did not match"
)

If you run: test.bat wrongpassword the output is: "wrongpassword did not match"

However, if you run: test.bat password the output is "password matched!"

Side Note: storing and checking a password like this would be a really really bad idea.

Teddy Ort
  • 756
  • 6
  • 7
0

You can do it with looping through your "test.txt" file on your desktop that could look as follows:

data1
data2
data3
data4
data5
data6
data7
data8
data9

And "test.bat" file then:

set /p @var= Add your input here: 
cls
ECHO Script initiated!
ECHO %@var%

cd "C:\Users\%USERNAME%\desktop"

:: loop over file line by line
for /f "tokens=*" %%a in (test.txt) do (
:: test if data exist in file
IF %@var%==%%a (
     echo data exists in txt file
    )
)
pause

Try to type as input: "data4" and you will see that after fourth loop data4 is outputed.

Marek Bernád
  • 481
  • 2
  • 8
  • 28