Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find text within string line

I have a text file, that has some text with this syntax:

mytextfile.txt:

websiteurl1 username1 password1  
websiteurl2 username2 password2                                       
websiteurl3 username3 password3

And so on....

And I'd like to be able to find username and password strings by pointing the websiteurl, so let's say I tell the batch file, find websiteurl3, it should print the username3 and password3 and I was able to write a "FOR LOOP" but I am not sure how to use the syntax of the loop, as my code finds only the last line always, here is what I have:

FOR /F "tokens=2,3 delims= " %%A IN (URL.txt) DO IF EXIST URL.txt (set WEBUserName1=%%A) && (SET WEBUserPass1=%%B)  
pause
echo Username:"%WEBUserName1%"
echo Password:"%WEBUserPass1%"
pause
exit

I know the loop is looking on the "URL.txt" for the tokens 2 and 3, and then sets the variables accordingly, what I'd like to know, is how I can use the loop, or if needed, any other command to be able to:

  • Find the "URL.txt file
  • Then find the specific string, in this case, the first word of the specified string line
  • Then find tokens 2 and 3 of that string line.
like image 521
Wolf Avatar asked Feb 15 '26 10:02

Wolf


1 Answers

And I'd like to be able to find username and password strings

Use the following batch file.

test.cmd:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=2,3" %%a in ('type mytextfile.txt ^| findstr "%1"') do (
  echo Username:"%%a"
  echo Password:"%%b"
  pause
  exit
  )
endlocal

Notes:

  • Pass the website URL string as a parameter to the batch file.
  • findstr is used to find the matching line from the file, so we only need to parse a single line using for /f.

Example usage and output:

F:\test>type mytextfile.txt
websiteurl1 username1 password1
websiteurl2 username2 password2
websiteurl3 username3 password3

F:\test>test websiteurl3
Username:"username3"
Password:"password3"
Press any key to continue . . .

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • findstr - Search for strings in files.
  • for /f - Loop command against the results of another command.
  • type - Display the contents of one or more text files.
like image 155
DavidPostill Avatar answered Feb 17 '26 07:02

DavidPostill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!