htan68
htan68

Reputation: 33

Pick a line from text file and set it as variable

I really have no idea how to make the result from the following text file in to a variable in my batch file.

First I need to run this WMIC line.

wmic PAGEFILE get AllocatedBaseSize /Value > test.txt

The result from test.txt occupies 6 lines, only the third line has the characters and this is the one I need to set as my variable.

Content of test.txt

AllocatedBaseSize=16328

Upvotes: 1

Views: 285

Answers (4)

htan68
htan68

Reputation: 33

Not sure if it is better to post this as a new topic. Now I am almost done with my batch script, for now I am testing on one target host. Batch file have issues with division and found this good script from http://helloacm.com/math-example-using-windows-batch-script/ . I barely understand how it works but no idea how to change the final result of the last echoed "echo %o%"

Example:

  • AllocatedBaseSize = 3931
  • CurrentUsage = 94
  • PeakUsage = 94

Here's the code from the link above, I changed the C value to 3:

setlocal

    set /a a=%CurrentUsage%
    set /a b=%AllocatedBaseSize%
    set /a c=3

    set /a d=a/b
    set o=%a%/%b%=%d%.


:work   
    set /a a=(a-d*b)*10
    if "%a%"=="0" goto clean_up
    set /a d=a/b
    set /a c=c-1
    if "%c%"=="0" goto clean_up
    set o=%o%%d%

    goto work

:clean_up
    echo %o%


endlocal

Now the problem is the script echoes "96/3931=0.02", I need to display the result as "CurrentUsagePct=0.02" or even better if I can display it as ""CurrentUsagePct=2.44"

If there is already a batch file here that does the same, will love to use as well.

Upvotes: 0

Stephan
Stephan

Reputation: 56188

wmic PAGEFILE get AllocatedBaseSize /Value |find "=" > test.txt

Another way to skin the cat (without creating a file):

for /f %%i in ('wmic PAGEFILE get AllocatedBaseSize ^|findstr "." ^|find /v "Allocated"') do set base=%%i

or in this case even easyier:

for /f %i in ('wmic PAGEFILE get AllocatedBaseSize ^|findstr "[0-9]"') do set as=%i

Upvotes: 0

MC ND
MC ND

Reputation: 70943

This will directly set the variable without an intermediate file

for /f "tokens=*" %%a in (
    'wmic PAGEFILE get AllocatedBaseSize /value^|find "="'
) do for %%b in (%%a) do set "AllocatedBaseSize=%%b"

echo %AllocatedBaseSize%

The double for loop is to eliminate an additional CR (0x0D) character and the end of the output lines from WMIC

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207660

To get the line you want into a file:

wmic PAGEFILE get AllocatedBaseSize /Value | FINDSTR "Allocated" > test.txt

To get the contents of the file into a variable:

set /p Base=<test.txt  

Upvotes: 0

Related Questions