Here is a simpler solution:
for /f "delims=: tokens=1,2" %A IN ('findstr /n "%uname%" Users.txt') do ( @set "number_of_line=%A" && @set "_uname=%B" )
Or, using find
instead of findstr
(quite complicated):
for /f "eol=- delims=[] tokens=1-2" %A IN ('find /n "%uname%" Users.txt') do ( @set "number_of_line=%A" && @set "_uname=%B" )
As in your post you have requested batch file code (you have double percent signs (%%
)) you can double the percent-signs of the variables.
Let me explain my code:
In both two loops, we parse output of commands. You should know the command-output-format and why using findstr
is much simpler.
findstr
- We use
/n
option with findstr
which tells it to echo
the line that found string specified.
- After
/n
option, we specify string that should be searched in specified after file.
- After that, we specify the file we want to search the specified string.
The output will be:
%line_number%:%content_of_line%
So, we parse it saying:
- DON'T PARSE
:
symbol into token with delims=:
option!
- Access the
line_number
with %(%)A
and content_of_line
with %(%)B
using tokens=1,2
option.
- Well known: specify variable letter add
IN
, then command to be parsed and set to variables number of line and its content.
find
- We use
/n
option with find
which tells it to echo
the line that found string specified.
- After
/n
option, we specify string that should be searched in specified after file.
- After that, we specify the file we want to search the specified string.
The syntax is quite similar, but the output is completely different!:
---------- %FILENAME_SPECIFIED_WITH_CAPITAL_LETTERS%
[%line_number%]%line_content%
So, here:
- We ignore lines starting with
-
with eol=-
option.
- We don't parse
[]
symbols into tokens with delims=[]
.
- We want to access
line_number
with %(%)A
and line_content
with %(%)B
, so, we add tokens=1,2
option.
- Then, continuing as above (well known).
For better understanding how these commands work, I suggest you to open a new cmd window and type:
for /?
find /?
findstr /?
Try some examples of yours with find
and finstr
to completely understand how they work.
Some interesting references for further reading: