Home > Enterprise >  Batch script parsing text with for loop
Batch script parsing text with for loop

Time:07-05

I'm stuck with an problem parsing text with for loop.

I have a folder containing Excel files named after customers, that needs to be archived/encrypted with passwords from the CSV file (pass.csv) structured as PASSWORD;CUSTOMER_NAME.

Idea is to generate a list of Excel files (dir.txt), match it with the customer name in pass.csv, extract the password and use it to make an encrypted 7zip archive for all the Excel files in the folder (dir.txt). If customer is not on the list, a new random password is generated.

I think there is an issue using GOTO(subroutine) within the for loop. Instead of going to next entry in dir.txt it ends the loop.

Can you please help me to correctly write this code? Thank you!!

setlocal EnableDelayedExpansion

dir /b *.xlsx > dir.txt

for /f "tokens=*" %%a in (dir.txt) do (
    for /f "tokens=*" %%w in (pass.csv) do (
        for /f "tokens=2 delims=;" %%z in ("%%w") do (
            IF "%%z"=="%%a" (
                for /f "tokens=1 delims=;" %%y in ("%%w") do (
                    set pass=%%y
                    GoTo NEXTSTEP
                )
            ) ELSE (set pass=!random!)
        )
    )

    :NEXTSTEP
    CLS
    ECHO  #  WORKING ON FILE: %%a
    ECHO  #  ENCRYPTED WITH PASSWORD: !pass!
    "C:\Program Files\7-Zip\7z" a -t7z -mhe=on -p!pass! "%%a".7z "%%a"
    PING loopback -n 2 > NUL
)

CodePudding user response:

This is untested, and only an assumption based upon what you've posted, but is this what you were trying to achieve:

If Not Exist "pass.csv" GoTo :EOF
SetLocal EnableDelayedExpansion
For /F "EOL=? Tokens=*" %%G In ('Dir "*.xlsx" /B /A:-D 2^>NUL') Do (
    %SystemRoot%\System32\findstr.exe /IL ";%%G" "pass.csv" 1>NUL && (
        For /F "Tokens=1-2 Delims=;" %%H In (
            '%SystemRoot%\System32\findstr.exe /IL ";%%G" "pass.csv"'
        ) Do If /I "%%I" == "%%G" Set "pass=%%H"
    ) || Set "pass=!RANDOM!"
    ClS
    Echo  #  WORKING ON FILE: %%G
    Echo  #  ENCRYPTED WITH PASSWORD: !pass!
    "%ProgramFiles%\7-Zip\7z.exe" a -t7z -mhe=on -p"!pass!" "%%~nG.7z" "%%G"
    %SystemRoot%\System32\PING.EXE loopback -n 2 1>NUL
)

CodePudding user response:

I managed to override the "syntax error" by putting random password as part of first loop - as "default". Real developers would roll their eyes, but it works. :D

for /f "tokens=*" %%a in (dir.txt) do (

set pass=!random!

    for /f "tokens=*" %%w in (pass.csv) do (

        for /f "tokens=2 delims=;" %%z in ("%%w") do (
            if "%%z"=="%%a" (
                for /f "tokens=1 delims=;" %%y in ("%%w") do (
                    set pass=%%y
                )
            )
        )
    )
  • Related