Altering values in .json files - batch-file

I have a simple question.
I have a config.json file with the below content
"DefaultAdminUsername": "Administrator#test.com",
"DefaultAdminPassword": "Admin!",
"DefaultNoOfUsers": "100",
I want to modify the value of "DefaultNoOfUsers" from a batch file
for example : Change from 100 to 1000
A pseudo code could be
for /f %%A in (config.json) do (
SET key = value
)
echo %VERSION%
echo %TEST%

Here is a little commented batch file for making this replacement in file config.json without checking for input mistakes.
#echo off
rem Exit this batch file if file config.json does not exist in current directory.
if not exist config.json goto :EOF
rem Make sure that the temporary file used does not exist already.
del "%TEMP%\config.json" 2>nul
rem Define a default value for number of users.
set "DefaultNoOfUsers=100"
rem Ask user of batch file for the number of users.
set /P "DefaultNoOfUsers=Number of users (%DefaultNoOfUsers%): "
rem Copy each line from file config.json into temporary file
rem with replacing on line with "DefaultNoOfUsers" the number.
for /F "tokens=1* delims=:" %%A in (config.json) do (
if /I %%A == "DefaultNoOfUsers" (
echo %%A: "%DefaultNoOfUsers%",>>"%TEMP%\config.json"
) else (
echo %%A:%%B>>"%TEMP%\config.json"
)
)
rem Move the temporary file over file config.json in current directory.
move /Y "%TEMP%\config.json" config.json >nul
rem Delete the used environment variable.
set "DefaultNoOfUsers="
Run in a command prompt window for /? and read entire help output in window to understand how the for loop works.

Related

Is there a way to create a persistent variable in batch file by writing to itself?

I have written a batch file that I use for file management. The batch file parses an .XML database to get a list of base filenames, then allows the user to move/copy those specific files into a new directory. The program prompts the user for a source directory and the name of the .XML file. I would like the program to default the variables to the last used entry, even if the previous CMD session has closed. My solution has been to ask the user for each variable at the beginning of the program, then write those variables to a separate batch file called param.bat at the end like this:
#echo off
set SOURCEDIR=NOT SET
set XMLFILE=NOT SET
if exist param.bat call param.bat
set /p SOURCEDIR=The current source directory is %SOURCEDIR%. Please input new directory or press [Enter] for no change.
set /p XMLFILE=The current XML database is %XMLFILE%. Please input new database or press [Enter] for no change.
REM {Rest of program goes here}
echo #echo off>param.bat
echo set SOURCEDIR=%SOURCEDIR%>>param.bat
echo set XMLFILE=%XMLFILE%>>param.bat
:END
I was hoping for a more elegant solution that does not require a separate batch file and allows me to store the variable data within the primary batch file itself. Any thoughts?
#echo off
setlocal
dir /r "%~f0" | findstr /c:" %~nx0:settings" 2>nul >nul && (
for /f "usebackq delims=" %%A in ("%~f0:settings") do set %%A
)
if defined SOURCEDIR echo The current source directory is %SOURCEDIR%.
set /p "SOURCEDIR= Please input new directory or press [Enter] for no change. "
if defined XMLFILE echo The current XML database is %XMLFILE%.
set /p "XMLFILE=Please input new database or press [Enter] for no change. "
(
echo SOURCEDIR=%SOURCEDIR%
echo XMLFILE=%XMLFILE%
) > "%~f0:settings"
This uses the Alternate Data Stream (ADS) of the batchfile to
save the settings.
NTFS file system is required. The ADS stream is lost if the
batchfile is copied to a file system other than NTFS.
The dir piped to findstr is to determine if the
stream does exist before trying to read from it.
This helps to avoid an error message from the for
loop if the ADS does not exist.
The for loop sets the variable names and values read from the ADS.
Finally, the variables are saved to the ADS.
Note:
%~f0 is full path to the batchfile.
See for /? about all modifiers available.
%~f0:settings is the batchfile with ADS named settings.
dir /r displays files and those with ADS.
Important:
Any idea involving writing to the batchfile could result
in file corruption so would certainly advise a backup of
the batchfile.
There is one way to save variables itself on the bat file, but, you need replace :END to :EOF
:EOF have a good explained in this link .:|:. see Where does GOTO :EOF return to?
Also, this work in fat32/ntfs file system!
You can write the variables in your bat file, and read when needs:
Obs.: Sorry my limited English
#echo off & setlocal enabledelayedexpansion
set "bat_file="%temp%\new_bat_with_new_var.tmp"" & type nul >!bat_file! & set "nop=ot Se"
for /f %%a in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo 0x40"') do set "delim=%%a"
type "%~f0"| findstr "!delim!"| find /v /i "echo" >nul || for %%s in (SOURCEDIR XMLFILE) do set "%%s=N!nop!t"
if defined SOURCEDIR echo/!SOURCEDIR!%delim%!XMLFILE!%delim%>>"%~f0"
for /f "delims=%delim% tokens=1,2" %%a in ('type "%~f0"^| findstr /l "!delim!"^| find /v /i "echo"') do (
set /p "SOURCEDIR=The current source directory is %%~a. Please input new directory or press [Enter] for no change: "
set /p "XMLFILE=The current XML database is %%~b. Please input new database or press [Enter] for no change: "
if /i "!old_string!" neq "!SOURCEDIR!!delim!!XMLFILE!!delim!" (
type "%~f0"| findstr /vic:"%%~a!delim!%%~b!delim!">>!bat_file!"
copy /y !bat_file! "%~f0" >nul
echo/!SOURCEDIR!!delim!!XMLFILE!!delim!>>%~f0"
goto :_continue_:
))
:_continue_:
rem :| Rest of program goes here | replace/change last command [goto :END] to [goto :EOF]
goto :EOF
rem :| Left 2 line blank above, because your variable will be save/read in next line above here |:

Batch Finding and displaying duplicate strings in file names

I have a question. Is it possibile in batch language to search in folder a part of name that is same like another file and display it.For example i got folder with files :
ggggggsss.mp3
ddddddeee.mp3
ddddddff.mp3
ssssssddd.mp3
aaaaasssss.mp3
11111ssdas.mp3
11111dddd.mp3
...
I need to display in cmd only names of files
ddddddeee
ddddddff
and
11111ssdas
11111dddddd
Because the first six letter are the same. Could someone help me with this problem?
Save this script to test.bat and run from open Cmd Prompt. Replace dir value with path to your folder with .mp3 files:
#echo off
setlocal enabledelayedexpansion
set "dir=%userprofile%\music"
set "pattern1=dddddd" & set "pattern2=11111"
pushd "%dir%"
FOR %%G IN (*.mp3) DO ( set song=%%G
if "!song:~0,6!"=="%pattern1%" echo %%G)
echo/
FOR %%G IN (*.mp3) DO ( set song=%%G
if "!song:~0,5!"=="%pattern2%" echo %%G)
popd
exit /b
See also Extract Substrings.

How to get the file name and the second line of all CSV files in directory into another CSV file?

I need to analyze the results provided in a list of CSV files where I need to have the file name and its second line, this for the set of files of the result directory in a single output. I found on Stack Overflow a piece of code to get the file name and a piece of code to get the second line of a file. Frankly it is beyond my knowledge to patch them together.
This is what I have so far:
setlocal enabledelayedexpansion
#echo "filename secondline"
for /f "delims=" %%a in ('dir /b /s *.*') do (#echo %%~nxa
set filename=%%~a
echo %filename%
pause
for /f "tokens=1,* delims=:" %i% in ('findstr /n /r . %filename%') do(if %i% geq 2 if %i% leq 2 echo %j% )
rem pause
)
endlocal
How to get the file name and the second line of all CSV files in directory into another CSV file?
It is not very clear what you want. So let me add some information about what I understood.
There are some CSV files in a directory like C:\Temp which is the current directory on executing the batch file which contains for example:
C:\Temp\DataFile1.csv
first name,second name,address,country
John,Doe,"20 Baker Street, Nowhere",Fantasy Island
x,y,anywhere,anyland
C:\Temp\DataFile2.csv
first name,second name,address,country
Jane,Doe,"5 Hammer Lane, Somewhere",Happy Island
x,y,anywhere,anyland
And in same directory one more CSV file with name ExtractionResults.csv should be created containing finally for this example:
"C:\Temp\DataFile1.csv",John,Doe,"20 Baker Street, Nowhere",Fantasy Island
"C:\Temp\DataFile2.csv",Jane,Doe,"2 Hammer Lane, Somewhere",Happy Island
The file names in first column should be quoted in case of one of the CSV files have a comma in file name.
For such a task the following commented batch file could be used:
#echo off
rem Name of results file without file extension with or without path.
set "ResultsFileName=ExtractionResults"
rem Delete a perhaps already existing results file from a previous run.
del "%ResultsFileName%.csv" 2>nul
rem Delete also a perhaps already existing temporary results file from
rem a not completed previous run. A temporary file with a file extension
rem different to CSV is used for the results in case of results file is
rem created also in current directory with file extension CSV. This must
rem be done to avoid that the second line of the results file is included
rem in the results, too.
del "%ResultsFileName%.tmp" 2>nul
rem Call for each CSV file in current directory the subroutine
rem GetSecondLine with full name of the CSV file.
for %%I in (*.csv) do call :GetSecondLine "%%~fI"
rem Use command MOVE instead of RENAME to rename the file in case of results
rem file name is specified at top with an absolute or relative path as the
rem command RENAME does not allow as second parameter a file name with path.
move /Y "%ResultsFileName%.tmp" "%ResultsFileName%.csv"
rem Exit this batch file and return to parent batch file or command processor.
goto :EOF
rem This is a subroutine. It prints to the temporary results file
rem just the second line or nothing if the file contains just 1 line.
rem The execution of goto :EOF results here in exiting the subroutine.
:GetSecondLine
for /F "usebackq skip=1 delims=" %%L in ("%~1") do (
echo "%~1",%%L>>"%ResultsFileName%.tmp"
goto :EOF
)
goto :EOF
Well, the code above contains more comment lines than commands. But for an even better understanding of the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
del /?
for /?
goto /?
move /?
rem /?
And read also the Microsoft article Using command redirection operators for an explanation of >> and 2>nul.

Batch file that will modify date in txt file

I have a line in a text file that I'm trying to modify using a batch file. The line in this case is the lastexportdate=2014-01-01. I'm trying to get the batch file to modify this from
lastexportdate=2014-01-01
to
lastexportdate= Current timestamp.
Is this possible to have this equal the timestamp of my computer? Not certain how to go about tackling this, so if anyone could help that would be awesome. I'm using Windows 7.
File contents below:
root.footer=</CREDITEXPORT>
root.header=<CREDITEXPORT>
emailaddronsuccess=test#test.com
emailaddronerror=test#test.com
rerunexportdate=2014-09-06
errorfilelocation=C:\\
lastexportdate=2014-01-01
xmloutputlocation=C:\\
#echo off
setlocal
rem getting current time stamp
set "beginJS=mshta "javascript:var t=new Date();var dd=t.getDate();var mm=t.getMonth()+1;var yyyy=t.getFullYear();if(dd^<10) dd='0'+dd;if(mm^<10) mm='0'+mm;close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write("
set "endJS=));""
:: FOR /F does not need pipe
for /f %%N in (
'%beginJS% yyyy+'-'+mm+'-'+dd %endJS%'
) do set cds=%%N
echo cds=%cds%
rem processing the file
rem set the location of the file
set "content_file=c:\some.file"
break>temp.file
for /f "usebackq tokens=1* delims==" %%a in ("%content_file%") do (
if "%%a" NEQ "lastexportdate" echo %%a=%%b>>temp.file
if "%%a" EQU "lastexportdate" echo %%a=%cds%>>temp.file
)
Not tested.Just change the location of the content_file and check if the created temp.file is ok.
To replace the file add move temp.file "%content_file%" at the end.

Batch script that moves each file in a folder into their own folders named after the file?

So if I have
/folder/file1.txt
/folder/file2.jpg
/folder/file3.py
I want to create
/folder/file1/file1.txt
/folder/file2/file2.jpg
/folder/file3/file3.py
I have this batch file (be careful where you run it), which mostly works but if there is whitespace in the file name, the folder name will only be named up until the whitespace and so the file won't be moved inside of it.
Also, I only got it to work by arbitrarily putting the word "Folder" or some random string at the end of the folder name, if I exclude that, for some reason it won't work. I'm on windows 7.
#echo off
for /f %%a in ('dir /a-d /b') do (
if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
)
goto :EOF
:func
set file=%~1
set dir=%file% Folder
md "%dir%" Folder 2>nul
move "%file%" "%dir%"
goto :EOF
Any ideas on how to address the whitespace/name issues? Thanks in advance.
#echo off
for /f "usebackq delims=?" %%a in (`dir /a-d /b`) do (
if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
)
goto :EOF
:func
set file=%~1
set dir=%file% Folder
md "%dir%" Folder 2>nul
move "%file%" "%dir%"
goto :EOF
By setting the delims=? you are saying that your delimiter is a ? to split up a string, instead of the whitespace character, which allows you to read full file names with spaces in them. Usebackq means that you instead use ` around the command to be ran, which to me, just makes it more logical to read and understand "Hey, I'm actually executing this string."
To avoid problems with spaces in paths/file names, double quote all the references to them.
The reason for having to include a string at the end of the folder in your code is you are trying to create a folder with exactly the same name that the file (in your code, you are not removing the extension), and you can not have two elements (files or folders) inside a folder with the same name.
#echo off
for %%a in ("c:\folder\*") do (
if not "%%~fa"=="%~f0" (
if not exist "%%~dpna\" echo md "%%~dpna"
if exist "%%~dpna\" echo move /y "%%~fa" "%%~dpna"
)
)
For each file in the indicated folder
if the file is not the batch file
if not exist a folder with the same name that the file, create it
if the target folder exist, move the file to the folder
%%~fa = full path of the file being processed
%~f0 = full path of the batch file
%%~dpna = drive, path, and file name without extension of the current file being proccesed
In this code, the reason for the third if is to check if the possible previous folder creation has failed. If you have a file with no extension, you will not be able to create the folder, as it will have exactly the same name as the file and this is not allowed.
Code includes echo commands before md and move to show what will be executed. If the output is correct, remove the echo to make it work.

Resources