Search code examples
windowsbatch-filecommand-linearchive7zip

How to archive files with 7zip directly for a .7z without extracting it?


I know how to archive files or to extract with 7zip (in Windows). I know that WinRAR tools can archive files from another archives. Something like

    winrar -a dest_archive.rar origin_archive.zip/toto.txt

This seems not possible with 7z. Currently here is what i'm trying

    "C:\Program Files\7-Zip\7z" a "toto.zip" tata.7z\tata.txt

I know i could extract the whole archive (with 'e' option) then archive the file i want but this extract operation is one too many.


Solution

  • 7-zip doesn't provide this functionality. You'd have to do it yourself. Here's a quick demo. The relative file path (in the source .7z) is the first argument. The other args are the 7-Zip archives (source, then dest).

    SETLOCAL 
    
    SET "FILE_TO_MOVE=%~1"
    SET "SOURCE_ARCHIVE=%~2"
    SET "TARGET_ARCHIVE=%~3"
    
    ECHO File: %FILE_TO_MOVE%
    ECHO Source: %SOURCE_ARCHIVE%
    ECHO Target: %TARGET_ARCHIVE%
    
    SET "TEMP_DIR=%TEMP%\7z_temp_%RANDOM%"
    IF EXIST "%TEMP_DIR%" RMDIR /S /Q "%TEMP_DIR%"
    MKDIR "%TEMP_DIR%"
    
    @ECHO Before copy...
    7z.exe l "%TARGET_ARCHIVE%
    
    7z.exe x -o"%TEMP_DIR%" "%SOURCE_ARCHIVE%" "%FILE_TO_MOVE%"
    pushd "%TEMP_DIR%"
    7z.exe a "%TARGET_ARCHIVE%" "%FILE_TO_MOVE%"
    popd
    RMDIR /S /Q "%TEMP_DIR%"
    
    @ECHO After copy...
    7z.exe l "%TARGET_ARCHIVE%
    

    One quirk about this solution is that the target will probably need to be a fully qualified path (because you're changing to a different directory before referring to it). Since I don't know precisely how you intend to perform this operation, I can't propose a better solution that specifying an absolute path.