Skip to content

Latest commit

 

History

History
executable file
·
145 lines (102 loc) · 3.47 KB

File metadata and controls

executable file
·
145 lines (102 loc) · 3.47 KB

(FOR, FOR /L, FOR /F)

  • 📌 Overview of FOR Variants

    Syntax Purpose
    FOR %%A IN (...) DO Loop over a set of items/files
    FOR /L %%A IN (start,step,end) DO Loop through numeric ranges
    FOR /F %%A IN (...) DO Loop through text files or command output

1. FOR %%A IN (...) DO

  • ✅ Syntax

    FOR %%A IN (item1 item2 item3) DO (
        ECHO Item: %%A
    )
  • 📁 Use Case: Iterate Files

    FOR %%F IN (*.txt) DO (
        ECHO Found text file: %%F
    )
    • Wildcards like * and ? are supported.
    • Double percent (%%) is used in batch files. In the command line, use single %.

2. FOR /L %%A IN (start,step,end) DO

  • This variant is similar to traditional C-style loops.

    ✅ Syntax

    FOR /L %%I IN (1,1,5) DO (
        ECHO Count: %%I
    )
    • (1,1,5) means start at 1, increment by 1, until 5.
    • You can count down too:
    FOR /L %%I IN (5,-1,1) DO (
        ECHO Reverse Count: %%I
    )

📄 3. FOR /F %%A IN (...) DO

  • Processes contents from:

    • A file
    • A string
    • The output of a command

    ✅ Reading Lines from a File

    FOR /F "tokens=1,2 delims=," %%A IN (data.csv) DO (
        ECHO Name: %%A, Age: %%B
    )

    Options:

    • tokens=n: Select which fields (words) to parse.
    • delims=,: Define delimiter character.
    • skip=n: Skip header lines.

    📜 Parsing Command Output

    FOR /F %%A IN ('DIR /B *.txt') DO (
        ECHO File: %%A
    )

    🔁 Nested Loops

    FOR %%I IN (A B) DO (
        FOR %%J IN (1 2) DO (
            ECHO %%I %%J
        )
    )

⚠️ Gotchas & Tips

  • Always double the % sign in batch files (%%A).

  • Wrap variables in quotes to handle spaces.

  • When reading from command output, FOR /F trims whitespace by default.

    To preserve spacing and empty lines, use usebackq and delims=.

    FOR /F "usebackq delims=" %%L IN ("my file.txt") DO (
        ECHO Line: %%L
    )

🧪 Real-World Examples

  1. Rename All .log to .bak

    FOR %%F IN (*.log) DO (
        REN "%%F" "%%~nF.bak"
    )
  2. Read IPs from File and Ping

    FOR /F %%I IN (ips.txt) DO (
        PING -n 1 %%I
    )

🧠 Summary Table

Type Example Use Case
File loop FOR %%F IN (*.txt) Process file list
Number loop FOR /L %%I IN (1,1,5) Count or iterate numerically
Text loop FOR /F %%L IN (file.txt) Read lines or command output