Touseef Para
Touseef Para

Reputation: 3

Write variables to txt file inside for loop in cmd

I want to write variables to multiple text file using batch, but it doesn't work

Set b=5
Set c=13
For /l %%a in (1, 1,100) do (
    Echo title
    Echo lambda 1.5406
    Echo cell %b% %c% 90.00 100.00
    Echo end of path
    b=%b% + 1
    c=%c% + 1
)> path%%a.txt

Plz help

Upvotes: 0

Views: 2415

Answers (2)

ScriptKidd
ScriptKidd

Reputation: 841

  1. In batch, one should always avoid whitespace, not to mention that you used whitespace the wrong way:
    Set b = 5 is setting %b % to  5

  2. The calculation of float is not supported in batch. To get around with it:

    • Pass to powershell and redirect the output to your file
    • Use my method below
  3. DelayedExpansion should be enabled.

Your script should look like:

@echo off
====SETLOCAL EnableDelayedExpansion
set/a"b=50, c=131"


for /L %%N in (1,1,100) do (
    echo(title
    echo(lambda 1.5406
    echo(cell !b:~0,-1!.!b:~-1! !c:~0,-1!.!c:~-1! 90.00 100.00
    echo(end of path
    set/a"b+=1, c+=1"
)>"path%%N.txt"

Shortened using the newline hack:

@echo off
====SETLOCAL EnableDelayedExpansion

( set LF=^
%= EMPTY =%
)
set/a"b=50, c=131"

for /L %%N in (1,1,100) do (
    echo(title!LF!lambda 1.5406!LF!cell !b:~0,-1!.!b:~-1! !c:~0,-1!.!c:~-1! 90.00 100.00!LF!end of path
    set/a"b+=1,c+=1"
)>"path%%N.txt"

Upvotes: 1

lit
lit

Reputation: 16226

It would seem unlikely that you will come to a successful result using cmd.exe batch script programming. If you are on a supported Windows system, PowerShell will be available.

=== donumbers.ps1

$b = 5
$c = 13.1

(1..100) |
    ForEach-Object {
        "title`nlambda 1.5406`ncell {0} {1} 90.00 100.00" -f @($b, $c) |
            Out-File -FilePath "C:/src/t/path$_.txt" -Encoding ascii
        $b = $b + 0.1
        $c = $c + 0.1
    }

Run it using:

powershell -NoLogo -NoProfile -File .\donumbers.ps1

Upvotes: 0

Related Questions