Little BlueCat
Little BlueCat

Reputation: 11

How to exclude file extension when using 7zip cmd line batch

I have a .batch script in my Send to folder on Windows which I use to compress multiple files in the folder to a .zip. The problem I'm having is, it's including the extension in the archive file name.

I've search on google, read a lot of posts on stackexchange etc and none of the solutions posted seem to work for me.

@echo off
for %%A in (*.*) do call :doit "%%A"
goto end

:doit
if "%~x1"==".bat" goto :eof
if "%~x1"==".7z" goto :eof
if "%~x1"==".zip" goto :eof
if "%~x1"==".rar" goto :eof
"C:\Program Files\7-Zip\7z.exe" a -tzip %1.zip %1 -sdel
goto :eof

:end

Myfile.txt -> MyFile.txt.zip

I want to remove the .txt from file name if possible.

Upvotes: 0

Views: 1440

Answers (2)

Compo
Compo

Reputation: 38643

I'm not sure of the syntax for your compressor program, because the answer you've accepted looks wrong both in the fact spaces aren't protected and %~n1 may be missing it's extension.

You could probably do this as a single line:

@For /F "Delims=" %%A In ('Dir /B/A-D-S-L "%~1"^|FindStr /IVE "\.7z \.bat \.rar \.zip"') Do @"%ProgramFiles%\7-Zip\7z.exe" a -tzip "%%~nA.zip" "%%~A" -sdel

Upvotes: 0

double-beep
double-beep

Reputation: 5510

You can use %~n1 which uses the filename only of the first argument. Here is a possible solution:

@echo off
for %%A in (*.*) do (call:doit "%%A")
goto end

:doit
if "%~x1" NEQ ".bat" (
    if "%~x1" NEQ ".7z" (
        if "%~x1" NEQ ".zip" (
            if "%~x1" NEQ ".rar" (
                "C:\Program Files\7-Zip\7z.exe" a -tzip %~n1.zip %~n1 -sdel

:end
exit /b 0

Upvotes: 1

Related Questions