windows command for grand total - windows

Is there a easy way to calculate the grand total of all the numberic values specified line by line using a windows command (or batch file - least prefer)
suppose
7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208
assume this is in a file
I want the total of all the values. thanks in advance

I'm not aware of any command line utility to compute such a sum. But you can use a for loop iterating through the file. Something like this will work but you will need a helper batch file. In Sum.bat dump:
REM. Turn off echo-ing of individual commands
#echo off
REM. Set variable a to 0. /a mean arithmetic expression
set /a sum = 0
REM. For loop updating the sum as we go
FOR /F %%i IN (file.txt) DO set /a sum += %%i
REM. Output
echo %sum%

Related

Command Prompt Search for files in a directory take the name of one random

Inside a directory c:\configs I have files with various extensions including the extension .rac. I need a script for the Windows command prompt that looks inside c:\configs for the names of the files that end with the extension .rac, ignoring other extensions. Then of all the names that end with .rac extension the script must choose a random one and process it with the command c:\programs\submit.exe namerandom.rac.
For example, suppose that random .rac file is called mosaic.rac, then the script executes the command c:\programs\submit.exe mosaic.rac. Of course the mosaic.rac name changes each time the script is runs because it is a random selected from the all the .rac files found.
Anyone have an idea in how to do and that can put example code?
#echo off
setlocal EnableDelayedExpansion & set n=0
for /f "delims=" %%a in ('dir /b /A-D "*.rac"') do (
set "f=%%a" & set "f[!n!]=!f!" & set /a "n+=1")
set /a c=%random% %% n
echo !f[%c%]!
Explanation:
Line #4: it make a pseudo array in f with n incremented by 1
Line #5: it take a random number between 0 and the total count of files called n with the help of: %random% modulo n
In this way, this creates a number of variables automatically according to their position then %random% %% n picks one.
You might as well picks some manually like this:
echo !f[0]! !f[1]! !f[2]! !f[3]! !f[4]! !f[5]! ...
To accomplish that, you may use the following...
Firstly, to get all .rac files, use the dir command. The /B switch specifies to output only a bare file list without any headers nor footers. If you want to search the given directory recursively, add the /S switch:
dir /B "C:\configs\*.rac"
Secondly, you need to count the number of returned .rac files. You can use a for /F loop (parsing the output of dir /B) together with set /A for that:
set /A COUNT=0
for /F "delims=| eol=|" %%L in (
'dir /B "C:\configs\*.rac"'
) do (
set /A COUNT+=1
)
Thirdly, you need to compute a random number in the applicable range. The built-in variable RANDOM retrieves a random number from 0 to 32767, so we need a little maths. The result will be a number from 0 to %COUNT% - 1:
set /A RNDNUM=%RANDOM%%%COUNT
Fourthly, you can use another for /F loop with the skip option to select a random file (we skip the previously calculated number RNDNUM of lines).
The if statement ensures that no skip option is provided in case the random number is 0.
The goto command ensures that only the selected file is passed to submit.exe. If you omitted it, every file after the selection would be passed over to submit.exe too, one after another:
if %RNDNUM% gtr 0 (
set SKIP=skip=%RNDNUM%
) else (
set SKIP=
)
for /F "%SKIP% delims=| eol=|" %%L in (
'dir /B "C:\configs\*.rac"'
) do (
start "" /WAIT "submit.exe" "%%~L"
goto :CONTINUE
)
:CONTINUE
Put together those parts to get the final script.
Type each command and append /? in command prompt to get the respective help text displayed.

How can I pad numbers with leading zeros, to a fixed length?

I've tried so sort this for the better part of the morning.
It is actually the same question as this one from 2013, to which no one replied:
batch script with FOR does not work
I'll do my best to format the code so that it is easy to follow and maybe I'll get an answer...
I am doing an archive project from our help desk ticket system.
For sorting purposes, the files will have the ticket number and the date.
However, the ticket number varies in length. To fix this, all ticket numbers are to be 6 digits, with the shorter numbers padded with preceding zeroes (i.e. 1234 becomes 001234).
I can get the ticket number, but I need to find its length to know how many zeroes to add.
This works:
echo off
set my_str=12345
set length=0
:Loop
if defined my_str (
set my_str=%my_str:~1%
set /A "length+=1"
goto Loop)
echo the string is %length% characters long
However, I get a bunch of ticket numbers in a list.
So, I read through this:
set statements don't appear to work in my batch file
And got lost reading this:
http://www.computing.net/howtos/show/batch-script-variable-expansion-win200-and-up/248.html
And I tried this:
setlocal enabledelayedexpansion
echo off
for /f %%a IN (test.txt) do (
set my_str=%%a
set length=0
:Loop
if defined my_str (
set my_str=!my_str:~1!
set /A "length+=1"
echo %length%
goto Loop)
echo the string is %length% characters long
)
But it only reads the FIRST line of test.txt
Why does the FOR /F loop fail?
How do I get it to work?
You do not need to know the length of the ticket number string (when you can assure it won't be longer than 6 characters), you can prefix 5 zeros and split off the last 6 characters then:
set my_str=12345
set my_str=00000%my_str%
set my_str=%my_str:~-6%
echo %my_str%
If you still want to get the string length, consult this post.
You cannot use goto within the for body as goto breaks the for loop context. However, you can call a sub-routine within for, which in turn may contain goto.
Your batch script does exactly what you are describing: reading the first line of a number of files (in your case, only the one file) and determining the length of the first line. I.e. you got the inner part of your for loop wrong.
I don't know the correct solution either but I think that this page may be of some help to you:
http://ss64.com/nt/for_f.html
I hope that helps.
This seems like a XY problem. Instead of worrying about calculating the length of a string, just use the built-in substring methods to create a padded string.
#echo off
setlocal enabledelayedexpansion
for /f %%a IN (test.txt) do (
set my_str=000000%%a
#echo !my_str:~-6!
)
The end result echo'ed will be a six-digit number left-padded with zeroes.

How do I get truly random numbers in batch?

Everyone uses random numbers at one point or another. So, I need some truly random numbers (not pseudo-random*) generated from the command prompt, I also want a system that generates letters in a code line the size of: set RANDOM=%random% %%2 +1. And am I just trying to catch a non-existent butterfly? *pseudo-random is random that relies on outside info like time, batch's random generator is pseudo-random based on time, to test this open 2 new notepad .bat and name this file 1.bat
1.bat
start 2.bat
#echo off
cls
echo %random%
pause
2.bat
#echo off
cls
echo %random%
pause
What's happening?!? Well this is pseudo-random, as long as there is NO delay between the opening of the batch files, the batch file's numbers will be the same.
You're basically asking for entropy pool, and your platform is Windows, right?
Best bet is to use CryptGenRandom() function, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa379942(v=vs.85).aspx. You could probably call it from Powershell
UPDATE
Apparently, there is a .NET wrapper for crypto, so you could use it from Powershell
[System.Security.Cryptography.RNGCryptoServiceProvider] $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$rndnum = New-Object byte[] 4
# Generate random sequence of bytes
$rng.GetBytes($rndnum)
# rndnum is filled with random bits
....
On powershell it's pretty easy,
You can use the cmdlet Get-Random by itself or specify range like 1..100 | Get-Random
Another option is to call the System.Random object directly:
$Random = New-Object System.Random
$Random.Next()
Well, you may program a Batch file version of one of the tons of existent methods that generate pseudo-random numbers, or look for one that may be programmed in a Batch file with no further complications like The Minimal Standard Random Number Generator, or a simpler version of it like these Two Fast Implementations, and even modify one of they to made it simpler!
#echo off
setlocal EnableDelayedExpansion
rem Pseudo random number generator based on "The Minimal Standard"
rem http://www.firstpr.com.au/dsp/rand31/p87-carta.pdf
rem Antonio Perez Ayala aka Aacini
rem Initialize values
set /A a=16807, s=40
rem APA Modification: use current centiseconds for initial value
for /F "tokens=2 delims=." %%a in ("%time%") do if "%%a" neq "00" set /A s=1%%a %% 100
rem Example of use: generate and show 20 random numbers
for /L %%i in (1,1,20) do (
call :RandomGen
echo !rand!
)
goto :EOF
:RandomGen
rem Multiply the two factors
set /A s*=a
rem If the result overflow 31 bits
if %s% lss 0 (
rem Get result MOD (2^31-1)
set /A s+=0x80000000
)
rem APA modification: return just the low 15 bits of result (number between 0..32767)
set /A "rand=s & 0x7FFF"
exit /B
Of course, I know this method is not comparable with most of the "standard" methods, but I think it is enough for simple Batch file applications, like games...
The problem indeed is that %RANDOM% is only pseudo-random and depends when it's called; if two scripts use it (more-less) at the same time, it will have the same value.
Instead, call PowerShell from your batch script:
#for /f "tokens=*" %%i in ('powershell -Command "(1..100 | Get-Random)"') do #(
set "trueRandomInteger_between_1_and_100=%%i"
)

Windows batch FOR loop on range through command line

I want to perform an operation multiple times from a command window. Common sense tells me that a FOR loop should be able to handle this. Sure enough, if I want to execute, say, myProg.exe, I can open a command window and use:
C:\> FOR %i in (1 2 3) DO myProg.exe
Easy.
But what if I want to execute myProg.exe 1000 times? I want to specify a range in the FOR loop, but I'm having trouble seeing how to do this.
Intuitively, it seems like I should be able to do something like one of the following:
C:\> FOR %i in (1 to 1000) DO myProg.exe
C:\> FOR %i in (1-1000) DO myProg.exe
But, of course, this doesn't work. The FOR loop interprets the list as 3 tokens and 1 token, respectively, so myProg.exe is only executed 3 times and 1 time, respectively.
Batch File Solution
It'd probably be easy to write some sort of batch (.bat) file:
SET COUNT=0
:MyLoop
IF "%COUNT%" == "1000" GOTO EndLoop
myProg.exe
SET /A COUNT+=1
GOTO MyLoop
:EndLoop
But isn't there an easy way to do this from the command line?
You can use the /l tag in your statement to make it loop through a set of numbers.
eg.
C:\> FOR /l %i in (1,1,1000) DO myProg.exe
This says loop through the range, starting at 1, stepping 1 at a time, until 1000
http://ss64.com/nt/for_l.html
for /l %%i in (1,1,100) do echo %%i
add another % sign before i to work

DOS - Trying to understand delimiters to find lowest line count inf files

I found a bug in a bat file I was writing and by accident found a fix however I don't understand why the fix worked.. Which is ultimately my question, or if there are other problems with this logic that I have not discovered.
The script does a line count in 2 or more files then the goal is to find the file with the lowest line count and later use that count in a variable later in the script as a parameter.
Example file 1 (9 lines):
Wrote,0
Wrote,1
Wrote,2
Wrote,3
Wrote,4
Wrote,5
Wrote,6
Wrote,7
Wrote,8
Example file 2 (10 lines):
Wrote,0
Wrote,1
Wrote,2
Wrote,3
Wrote,4
Wrote,5
Wrote,6
Wrote,7
Wrote,8
Wrote,9
The main difference that I see is that lines 9 & 10 in file 2 are two digit line numbers
NOTE: I am not referring to the actual value on each line but only the line number's count value as my code does not try to parse the lines but only get the line count.
Near the top of the code I create then append the count values for each file into a temp file called ~numbers.txt so to simulate that process here assume my starting code is:
echo 9 > ~numbers.txt
echo 10 >> ~numbers.txt
type ~numbers.txt
So now I have a file with two lines "9" and "10" and of course 9 is lower than 10 but it also is one digit less than 10.
Now I attempt to find the lowest number contained in the file ~numbers.txt by reading the 1st line into a variable then looping and evaluating if current value is less than prior value.
setlocal enabledelayedexpansion
set /p lowest=<~numbers.txt
FOR /F "delims=" %%G in (~numbers.txt) DO IF %%G LSS !lowest! SET lowest=%%G
echo lowest num = %lowest%
When I run this code I get this output which is wrong:
lowest num = 10
What I have found is that if I remove the "delims=" from the FOR loop I will get the correct result of 9.
ALSO and what really screws up my understanding of the problem; If I only change the values in ~numbers.txt to 10 and 100 and leave the FOR loop line alone (keeping "delims=" ) then I get the correct value of 10 as my answer???
This is bad because it implies that my logic is flawed and that other number combinations will also yield different results.
Can anyone explain to me why this is the case and/or give an example on how to get the correct lowest number regardless of the values?
Thanks...
If you don't see something it doesn't mean it doesn't exist. (I'm talking of spaces here)
Try this instead:
> ~numbers.txt echo 9<press ENTER immediately>
>> ~numbers.txt echo 10<press ENTER immediately>
This will be truly WYSIWYG, no spaces at the end of line, no text comparisons by if because strings are not all numbers.
Of course, stripping the spaces with default delims (one of which is a space) also works fine as you have noticed already.
Consider this way of determining lowest line count:
set /a minlines=0x7FFFFFFF
for /f "tokens=2 delims=:" %%a in ('find /c /v "" *.txt') do set /a minlines="%%a-(minlines-%%a)*(minlines-%%a>>255)"
echo %minlines%
Note: no ifs, no delayed expansion

Resources