-->

Compress separately files within subfolders

2019-09-18 01:53发布

问题:

Hi all and thanks for the answers,

Firstly, I tried to find the answer to my problem but I did not find anything.

I have a tree of folders and sub-folders and I want to use 7zip to compress the files within those folders separately.

I have got this piece of code from this very website, it does what I want to get but it places the compressed files on the main folder:

    set extension=.*
    for /R %%a in (*%extension%) do "%sevenzip%" a -mx "%%~na.zip" "%%a"

I wonder if I can get a zip file of every file and have it in the sub-folder containing the source file. Or doing the process above and place every zip file inside the appropriate sub-folder.

I tried with a double 'For /d' but I was unable to get it:

    cd /d %~dp0

    rem 7z.exe path

    set sevenzip=

    if "%sevenzip%"=="" if exist "%ProgramFiles(x86)%\7-zip\7z.exe" set 

    sevenzip=%ProgramFiles(x86)%\7-zip\7z.exe


    if "%sevenzip%"=="" if exist "%ProgramFiles%\7-zip\7z.exe" set 

    sevenzip=%ProgramFiles%\7-zip\7z.exe


    if "%sevenzip%"=="" echo 7-zip not found&pause&exit

    for /D %%O in (*) do (

        for /R %%I in ("%%O\*") do (
            "%sevenzip%" a -mx "%%~na.zip" "%%a"

            ::        rd /s /q "%%I"  **Because I do not want to delete anything by now.

        )
    )

Again, thank you.

Alex.

回答1:

If you have somewhat complex folder structure then you probably better use plain list from dir:

  dir /a:-d /s /b /o

Just use its output in for:

for /f %%f in ('dir /a:-d /s /b /o') do (
  echo %%f <-- %%f is a full path to a file, do something with it
)

Btw, 7zip has useful option -sdel to remove the source file when archive has been created successfully.



回答2:

This is the final code:

@echo off

cd /d %~dp0

rem 7z.exe path

set sevenzip=

if "%sevenzip%"=="" if exist "%ProgramFiles(x86)%\7-zip\7z.exe" set sevenzip=%ProgramFiles(x86)%\7-zip\7z.exe

if "%sevenzip%"=="" if exist "%ProgramFiles%\7-zip\7z.exe" set sevenzip=%ProgramFiles%\7-zip\7z.exe

if "%sevenzip%"=="" echo 7-zip not found&pause&exit

@echo searching...

for /R %%I in (*) do (
    "%sevenzip%" a -mx -mmt4 "%%I.7z" -r -x!*.bat "%%I"

)

del "Compressing_files_7zip.bat.7z"*

del *.7z.7z

del *.zip.7z

::::::::::::::::::::::::::For setting up shutdown 60' after the end of the process.Remove colons in the line below. ::shutdown.exe /s /t 3600

pause

Thanks all for the support, especially to Frost.



回答3:

For a simpler version without using 7zip:

for /f %%f in ('dir /a:-d /s /b /o *.mdb') do (
    zip -r -p "%%f.zip" "%%f"
)