Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does substring in for not work?

Using this batch file I want zip some *.txt files. Each *.txt file in its own zip file. Unfortunately it is not working and i get as output

ECHO is disabled (OFF).

several times. Here is the sourcecode:

@echo off
setlocal EnableDelayedExpansion

for %%i in (*.txt) do (
    set filename = %%i
    set filenametrunc = %filename:~0,10%

    7z a -tzip -mx0 %zipname%
    echo %filename% zipped.
)

I read something about EnableDelayedExpansion and activated it. Can't get it working though.

Any help appreciated.

like image 307
Jonas Gröger Avatar asked Dec 09 '22 03:12

Jonas Gröger


1 Answers

You need to use SetLocal EnableDelayedExpansion and wrap variables in !. Also, don't put spaces between variable names, equals and the value.

set filename = ... makes a variable named %filename % with a value  ...
set filename=..... makes a variable named %filename% with a value .....

@echo off
setlocal EnableDelayedExpansion

for %%i in (*.txt) do (
    set filename=%%i
    set filenametrunc=!filename:~0,10!

    7z a -tzip -mx0 !zipname!
    echo !filename! zipped.
)

Variables in % inside brackets are evaluated all at the same time, which is before the entire loop starts executing. Your previous code would expand all variables before the set statement ran.

like image 183
Hand-E-Food Avatar answered Jan 02 '23 02:01

Hand-E-Food