(May 4, 2015 05:00 AM)HacksBro Wrote: I tried it and it works, but is it possible that I can set it to a variable? For example. I have a text file called playerName then inside it is Ali or whatever. Then I do this command:
Code
@ECHO OFF
TYPE C:\Users\Ali\Desktop\playerName.txt
SET playerName=0
SET TYPE=%playerName%
Could I do something like that?
Couldn't I use a FOR /L instead of the command TYPE? Would it affect my script?
When you use the
type command, it echoes a number of lines of text onto the screen - one line for each line in the text file. (Captain Obvious! But for clarity, I am stating this anyway)
If you want to process a bunch of lines of text and somehow extract a variable from it, the best method of doing that is with the
for /f loop.
for /f is used to process some lines of text.
The text can be a text file, or the output from a command, or a single line of text that is specified manually.
So for example, suppose you had a text file that contains the following text:
chatLog.txt
Code
CHAT LOG
MSG Jane 10:13 Hi Jim!
END CHAT LOG
This shows an example chat log, from which the script would parse information.
Suppose we want to capture the name "Jane":
Code
for /f "tokens=1,2,3*" %%a in ('type chatLog.txt') do (if "%%a" == "MSG" set name=%%b)
echo %name%
That is going to split each line of text up into
FOUR CHUNKS.
The chunks will be referred to as %%a, %%b, %%c and %%d.
Perhaps you wonder why "1,2,3*" means there will be 4 tokens. We only have numbers 1-3 after all.
The reason is the asterisk symbol at the end (*). This tells batch "just chuck everything else on the line into the next token".
This is useful for us because we can then have the message as the last thing to appear on the line, and it can have spaces in it, and they will not be treated as delimiters between tokens.
So lets walk through the process that the
for /f loop will use.
It processes the first line, and splits up the text into chunks (or "tokens"):
%%a = CHAT
%%b = LOG
%%c =
%%d =
Now it checks if "CHAT" is equal to "MSG", and it isn't, so it does nothing.
OK, NEXT LINE!
%%a = MSG
%%b = Jane
%%c = 10:13
%%d = Hi Jim!
Once again, we check if "%%a" == "MSG"
That evaluates to if "MSG" == "MSG", and this time IT'S TRUE!!
So we then set a variable called
%name% and the value is
Jane.
Finally, we process the 3rd line.
%%a = END
%%b = CHAT
%%c = LOG
%%d =
We are therefore checking if "END" == "MSG" and that returns false, so it does nothing.
Done!
Now we echo %name% and sure enough, there is Jane. :>