I would like to extract what users are online based on this text file:
https://minecraft-statistic.net/en/server/167.114.43.185_25565/json/
I will save it as a text file. Inside that there is something:
"players_list":["Raskhol"]["Lukaka"],"map":...etc
I would like to extract all the text between "_list": and ,"map" and set it as a variable. So that when I call the variable %Playerlist%, it would say:
["Raskhol"]["Lukaka"]
similar to #geisterfurz007's answer, this one assumes the you are after the first instance of "players_list": before the first instance of ,"map"
#Echo Off
Set/P var=<some.json
Set var=%var:,"map"=&:%
Set var=%var:*"players_list":=%
Echo=%var%
Timeout -1
Not tested due to beeing on phone.
#echo off
For /f "delims=: tokens=2" %%g in (PathTo\file.txt) do (
Set var=%%g
Goto:next
)
:next
Set var=%var:,map=%
echo %var%
Assumes players are the first to be listed.
Reads the file, takes the part after the first : up to the second one, stores it in var.
Then ,map gets replaces with nothing to result in just the players beeing echoed in the end.
Feel free to ask questions if something is unclear! Might take a while as I am currently mobile though.
This is a very simple batch file I did to start practicing with the command line, but for some reason it wont work properly. Here the code:
::Change names
#echo off
set /p DirLoc = "Enter file location:"
cd %DirLoc%
echo %DirLoc%
dir
set /p SetFrom = "What file type is it?"
set /P SetTo = "What file type do you want?"
echo Change from %SetFrom%
echo to %SetTo%
rename *.%SetFrom% *.%SetTo%
echo process has been completed
pause
echo on
For some reason, when I insert the folder location, which in my case is "C:\Users\Marco DS\Desktop\Test", the program will only go till "C:\Users\Marco DS\Desktop", which is no good. I have tried a few alternatives of my entries, but I never manage to get the desired directory.
Thanks for any suggestions.
Part of your problem is that, in Batch, you should not use spaces or quotation marks when setting variables, or else they will be part of the variable. Unlike many languages, Batch reads all whitespace characters as part of the code. In this case, the name of the variable is set as %DirLoc % instead of just %DirLoc%. In order to make your code work in the way you want, you need to remove all the unwanted spaces and quotation marks in your code.
For example:
set /p DirLoc = "Enter file location:" becomes set /p DirLoc=Enter file location:
To see proof of this, try writing echo %DirLoc % right after echo %DirLoc% and running the code.
I have a batch file that runs several python scripts that do table modifications.
I want to have users comment out the 1-2 python scripts that they don't want to run, rather than removing them from the batch file (so the next user knows these scripts exist as options!)
I also want to add comments to bring to their attention specifically the variables they need to update in the Batch file before they run it. I see that I can use REM. But it looks like that's more for updating the user with progress after they've run it.
Is there a syntax for more appropriately adding a comment?
Use :: or REM
:: commenttttttttttt
REM commenttttttttttt
BUT (as people noted):
if they are not in the beginning of line, then add & character:
your commands here & :: commenttttttttttt
Inside nested parts (IF/ELSE, FOR loops, etc...) :: should be followed with normal line, otherwise it gives error (use REM there).
:: may also fail within setlocal ENABLEDELAYEDEXPANSION
The rem command is indeed for comments. It doesn't inherently update anyone after running the script. Some script authors might use it that way instead of echo, though, because by default the batch interpreter will print out each command before it's processed. Since rem commands don't do anything, it's safe to print them without side effects. To avoid printing a command, prefix it with #, or, to apply that setting throughout the program, run #echo off. (It's echo off to avoid printing further commands; the # is to avoid printing that command prior to the echo setting taking effect.)
So, in your batch file, you might use this:
#echo off
REM To skip the following Python commands, put "REM" before them:
python foo.py
python bar.py
No, plain old batch files use REM as a comment. ECHO is the command that prints something on the screen.
To "comment out" sections of the file you could use GOTO. An example of all these commands/techniques:
REM it starts here the section below can be safely erased once the file is customised
ECHO Hey you need to edit this file before running it! Check the instructions inside
ECHO Now press ctrl-c to interrupt execution or enter to continue
PAUSE
REM erase the section above once you have customised the file
python executed1.py
ECHO Skipping some stuff now
GOTO End
python skipped1.py
python skipped2.py
:END
python executed2.py
What can I say? batch files are a relic of times long gone, they're clunky and ugly.
You can read more on this website.
EDIT: modified the example a bit to have it contain the elements you are apparently looking for.
The :: instead of REM was preferably used in the days that computers weren't very fast.
REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.
And as said in the first comment: you can add info to any line you feel the need to
SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS
As for the skipping of parts.
Putting REM in front of every line can be rather time consuming.
As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.
SOME CODE
GOTO LABEL ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL
SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP
:LABEL
CODE TO EXECUTE
Multi line comments
If there are large number of lines you want to comment out then it will be better if you can make multi line comments rather than commenting out every line.
See this post by Rob van der Woude on comment blocks:
The batch language doesn't have comment blocks, though there are ways
to accomplish the effect.
GOTO EndComment1
This line is comment.
And so is this line.
And this one...
:EndComment1
You can use GOTO Label and :Label for making block comments.
Or, If the comment block appears at the end of the batch file, you can
write EXIT at end of code and then any number of comments for your
understanding.
#ECHO OFF
REM Do something
•
•
REM End of code; use GOTO:EOF instead of EXIT for Windows NT and later
EXIT
Start of comment block at end of batch file
This line is comment.
And so is this line.
And this one...
Putting comments on the same line with commands: use & :: comment
color C & :: set red font color
echo IMPORTANT INFORMATION
color & :: reset the color to default
Explanation:
& separates two commands, so in this case color C is the first command and :: set red font color is the second one.
Important:
This statement with comment looks intuitively correct:
goto error1 :: handling the error
but it is not a valid use of the comment. It works only because goto ignores all arguments past the first one. The proof is easy, this goto will not fail either:
goto error1 handling the error
But similar attempt
color 17 :: grey on blue
fails executing the command due to 4 arguments unknown to the color command: ::, grey, on, blue.
It will only work as:
color 17 & :: grey on blue
So the ampersand is inevitable.
You can comment something out using :: or REM:
your commands here
:: commenttttttttttt
or
your commands here
REM commenttttttttttt
To do it on the same line as a command, you must add an ampersand:
your commands here & :: commenttttttttttt
or
your commands here & REM commenttttttttttt
Note:
Using :: in nested logic (IF-ELSE, FOR loops, etc...) will cause an error. In those cases, use REM instead.
You can add comments to the end of a batch file with this syntax:
#echo off
:: Start of code
...
:: End of code
(I am a comment
So I am!
This can be only at the end of batch files
Just make sure you never use a closing parentheses.
Attributions: Leo Guttirez Ramirez on https://www.robvanderwoude.com/comments.php
Commenting a line
For commenting line use REM or :: though :: might fail inside brackets
within delayed expansion lines starting with !<delimiter> will be ignored so this can be used for comments:
#echo off
setlocal enableDelayedExpansion
echo delayed expansion activated
!;delayed expansion commented line
echo end of the demonstration
Comment at the end of line
For comments at the end of line you can again use rem and :: combined with &:
echo --- &:: comment (should not be the last line in the script)
echo --- &rem comment
Commenting at the end of file
As noting will be parsed after the exit command you can use it to put comments at the end of the file:
#echo off
echo commands
exit /b
-------------------
commnts at the end
of the file
------------------
Inline comments
Expansion of not existing variables is replaced with nothing ,and as setting a variable with = rather hard you can use this for inline comments:
#echo off
echo long command %= this is a comment =% with an inline comment
Multiline comments
For multiline comments GOTO (for outside brackets) and REM with conditional execution (for inside brackets) can be used. More details here:
#echo off
echo starting script
goto :end_comments
comented line
one more commented line
:end_comments
echo continue with the script
(
echo demonstration off
rem/||(
lines with
comments
)
echo multiline comment inside
echo brackets
)
And the same technique beautified with macros:
#echo off
::GOTO comment macro
set "[:=goto :]%%"
::brackets comment macros
set "[=rem/||(" & set "]=)"
::testing
echo not commented 1
%[:%
multi
line
comment outside of brackets
%:]%
echo not commented 2
%[:%
second multi
line
comment outside of brackets
%:]%
::GOTO macro cannot be used inside for
for %%a in (first second) do (
echo first not commented line of the %%a execution
%[%
multi line
comment
%]%
echo second not commented line of the %%a execution
)
I prefer to use:
REM for comments
&REM for inline comments
Example:
#echo off
set parameter1=%1%
REM test if the parameter 1 was received
if defined parameter1 echo The parameter 1 is %parameter1% &REM Display the parameter
This is an old topic and I'd like to add my understanding here to expand the knowledge of this interesting topic.
The key difference between REM and :: is:
REM is a command itself, while :: is NOT.
We can treat :: as a token that as soon as CMD parser encounters the first non-blank space in a line is this :: token, it will just skip the whole line and read next line. That's why REM should be followed by at least a blank space to be able to function as a comment for the line, while :: does not need any blank space behind it.
That REM is a command itself can be best understood from the following FOR syntax
The basic FOR syntax is as follows
FOR %v in (set) DO <Command> [command param]
here <Command> can be any valid command
So we can write the following valid command line as rem is a command
FOR %i in (1,2,3) DO rem echo %i
However, we CANNOT write the following line as :: is not a command
FOR %i in (1,2,3) DO :: echo %i
You can use :: or rem for comments.
When commenting, use :: as it's 3 times faster. An example is shown here
Only if comments are in if, use rem, as the colons could make errors, because they are a label.
Ok so I am creating a script with a built in updater, it creates a new file with the following code and updates several variables, but for some reason this isn't working anyone have any idea how to fix it or a similar script that will do roughly the same thing.
#echo off
setlocal enabledelayedexpansion
set /p "findthis"="1"
set /p "replacewith"="1.2.3"
call:updater
set /p "findthis"="2"
set /p "replacewith"="2.3.4"
call:updater
set /p "findthis"="3"
set /p "replacewith"="3.4.5"
call:updater
goto:eof
:updater
for /f "tokens=*" %%a in (updateme.bat) do (
set write=%%a
if %%a==%findthis% set write=%replacewith%
echo !write!
echo !write! >>%~n1.replaced%~x1
)
goto:eof
there are several errors in this BAT.
Some are obvious syntax errors.
Read help set and correct all the set /p "this"="value" (hint: don't use /p option and correct the usage of " in the variable name)
you try to use %1 in a CALLed label. This is a passed parameter, and you are not passing it in your CALL. Read HELP CALL.
Some are logic errors.
The :updater code appends the updated string to the output file. It does so three times, so the final code is three times the original code with the strings changed.
Also, the code does try to find the string as a full line, a line containing just "1" in a BAT file does not make too much sense to me. You would probably want to find any text occurrence of "1".
Also, when you fix the previous problems, and if I understand correctly the intention of the code, you will eventually replace all "1" to "1.2.3" and then you replace all "2" to "2.3.4", so the original "1" will get replaced by "1.2.3.4.3".. and later on again, so it will finally be "1.2.3.4.5.4.3.4.5". Be careful with that.
How would I set a each line of a text document to separate variables using Batch? I know how to set a variable to the first line of a text document using:
Set /p Variable=<Test.txt
...but I don't know how to read other lines of the file. Lets say for example I had a text document with 3 lines, the first line had 'Apples' written on it, the second had 'Bananas' and the third had 'Pears', and lets say the document was called Fruit.txt. How would I set the variable 'Line_1' to the first line of the document, 'Line_2' to the second line and 'Line_3' to the last line?. Just to keep it simple, lets just say the batch file and Fruit.txt are both in the same folder. I don't want to do this in VBScript, so please only post Batch code. I would have thought that it would be something like:
#Echo off
Set /p Line_1=<Fruit.txt:1
Set /p Line_2=<Fruit.txt:2
Set /p Line_3=<Fruit.txt:3
Echo Fruit 1 is %Line_1%, Fruit 2 is %Line_2% and Fruit 3 is %Line_3%
Pause
Exit
...but quite clearly it isn't. Any help?
EDIT: This is for arbitrary-length files, then. jeb has an answer that solves your particular problem for a known number of lines. I will leave this here, though, as I hate deleting posts I put some time into for explanation :-)
Well, you obviously need some sort of counter. Let's start with 1:
set Counter=1
Then, you need to go line-wise through the file:
for /f %%x in (somefile) do ...
Then store the line in a numbered variable (that's what we have the counter for):
set "Line_!Counter!=%%x"
aaaaand increment the counter:
set /a Counter+=1
And that's it. Add a few more necessary things, you know, the boring stuff that's always needed in such cases (strange statements before and after, block delimiters, etc.), and you're done:
#echo off
setlocal enabledelayedexpansion
set Counter=1
for /f %%x in (somefile) do (
set "Line_!Counter!=%%x"
set /a Counter+=1
)
set /a NumLines=Counter - 1
Echo Fruit 1 is %Line_1%, Fruit 2 is %Line_2% and Fruit 3 is %Line_3%
rem or, for arbitrary file lengths:
for /l %%x in (1,1,%NumLines%) do echo Fruit %%x is !Line_%%x!
Some explanation:
set /p Var=<file will set the variable to the first line of a file, as you noted. That works because set /p will prompt for input and < file will redirect the file into standard input of a command. Thus set /p will interpret the file's contents as the entered input up until the user hits Return (i.e. the file contains a line break). That's why you get the first line. The system would throw the whole file at set /p but since the command only reads the first line and then is done they just get discarded.
The syntax you were proposing there is actually for accessing Alternate Data Streams of files on NTFS, which is somethhing totally different.
<short-detour> However, jeb has a way of reading multiple lines. This works because the block (delimited by parentheses) is a single command (see below) you can redirect a file's contents into. Except that command is comprised of multiple statements, each of which will read a single line and store it away. </short-detour>
Which brings us to for /f which iterates over the contents of a file (or the output of a command) line by line and executes a command or block of commands for each line. We can now read the whole file into as many variables as there are lines. We don't even need to know how many in advance.
You may have noticed the Line_!Counter! in there which uses Counter a little bit differently from how you're used to use environment variables, I guess. This is called delayed expansion and is necessary in some cases due to how cmd parses and executes batch files. Environment variables in a command are expanded to their values upon parsing that command. In this case the whole for /f including the block containing two statements is a single command for cmd. So if we used %Counter% it would be replaced by the value Counter had before the loop (1) and never change while the loop is running (as it is parsed once and run multiple times. Delayed expansion (signaled by using ! instead of % for variable access changes that and expands environment variables just prior to running a command.
This is almost always necessary if you change a variable within a loop and use it within the same loop again. Also this makes it necessary to first enable delayed expansion which is done with the setlocal command and an appropriate argument:
setlocal enabledelayedexpansion
set /a will perform arithmetic. We use it here to increment Counter by one for each line read.
To read multiple lines with set/p you need brackets around the set/p block.
#Echo off
(
Set /p Line_1=
Set /p Line_2=
Set /p Line_3=
) <Fruit.txt
Echo Fruit 1 is %Line_1%, Fruit 2 is %Line_2% and Fruit 3 is %Line_3%