Jonas Gröger
Jonas Gröger

Reputation: 1628

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.

Upvotes: 4

Views: 6116

Answers (3)

dbenham
dbenham

Reputation: 130889

Delayed expansion is only needed within the loop if you need to access a variable that you assign inside the loop. But there is no need in your case.

You need to 1st get the correct 7z syntax. Your original code was attempting to put all of the the files in the current directory into a single zip file because you didn't specify a filename. Also your ZIPNAME was uninitialized. You want something like the following.

7z a -tzip zipname filename

I presume you want the name of the zip to be the same as the original filename, except with a .zip prefix instead of .txt. Then all you need is the ~n modifier that gives the base name without the prefix. 7-Zip will automatically append the .zip extension.

for %%i in (*.txt) do 7z a -tzip %%~ni %%i

If you want you can add the -mx0 option, which does no compression. I can't imagine why you would do that for a text file.

for %%i in (*.txt) do 7z a -mx0 -tzip %%~ni %%i

If you want to add your own message

for %%i in (*.txt) do (
  7z a -mx0 -tzip %%~ni %%i
  echo %%i zipped into %%~ni.zip
)

Upvotes: 3

Hand-E-Food
Hand-E-Food

Reputation: 12814

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.

Upvotes: 7

PA.
PA.

Reputation: 29349

You need to initialize the variable zipname and expand the var using the ! character instead of the % character.

Read HELP SET, specifically

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time.

and change your code to

@echo off
setlocal EnableDelayedExpansion
for %%i in (*.txt) do (
    set zipname=%%i
    7z a -tzip -mx0 !zipname!
    echo !zipname! zipped.
) 

Upvotes: 4

Related Questions