Search code examples
windowsscripting7zip

Console command to extract only a single file from archive? (7z)


I have a script to extract all the archives in a folder to folders with names of the archives, I want to modify that so it will extract only a single file from each archive (doesn't matter which one), it will behave as if there's a counter that will count 1 file and move to the next archive.

For example say we have the following files in the folder, each archive contains what's in the curly braces:

a.7z {folder{1.txt, 2.txt, 3.txt}}
b.7z {folder2{4.txt, 5.txt, 6.txt}}
c.7z {7.txt}

So running the script will result in having the following extracted (those are folders):

a{folder{1.txt}}
b{folder2{4.txt}}
c{7.txt}

Is this possible?

This is the script I currently have:

PATH %PATH%;"C:\Program Files\7-Zip";
7z x *.* -o*

Solution

  • You can list the files of the archive using

    7z l a.7z
    

    If all the files end with txt, you can use

    7z l a.7z | find "txt"
    

    Use this answer to get the first line: Windows batch command(s) to read first line from text file

    Then use this answer to get the file name (last word) from the line and save it in a batch variable FILE_NAME: https://superuser.com/questions/667494/batch-to-extract-a-word-from-a-string-inside-a-text-file

    Then use the following command to extract the file:

    7z e -i!%FILE_NAME% a.7z -o*
    

    You can use this example to iterate all the *.7z files Iterate all files in a directory using a 'for' loop

    for /r %%i in (*.7z) do echo %%i
    

    All the parts together:

    @echo off
    
    for  %%i in (*.7z) do call :extract_file %%i
    
    :extract_file
    "c:\Program Files\7-Zip\7z.exe" l %1 > temp.txt
    for /f "skip=15 tokens=1-10" %%a in (temp.txt) do (
      echo %%f
      "c:\Program Files\7-Zip\7z.exe" e -i!%%f %1 -o*
      goto :end
    )
    :end
    EXIT /B 0
    
    :eof