Search code examples
linuxarchiveunzip

How to extract last file added to an zip archive


I have a monthly archive, that each day a new file is added to the archive. Occasionally I have to extract the last file added. The file name are random so I do not know what the file name is. I use this process.

Step 1 unzip -l /path/to/archive/dec2020.zip gives me list of files in archive and I write down last one added ie. latest_file.dat

Step 2 unzip /path/to/archive/dec2020.zip latest_file.dat I then extract that file from the archive.

what I would like to do is do this in one command, basically I want to extract the last file added to an archive in one command on a Linux machine.


Solution

  • Try this:

    unzip /path/to/archive/dec2020.zip $(unzip -l /path/to/archive/dec2020.zip | sort -k2 | tail -5 | head -1 | awk '{ print $4 }')
    

    $() expands the first command and uses the expansion in the second. We list the archive entries in date order and use tail, head and sort to get the line required. We then use awk to print out the file path (the 4th space delimited field)

    Alternatively, this can be done with the awk system function to action the unzip.

     unzip -l /path/to/archive/dec2020.zip | sort -k2 | tail -5 | head -1 | awk '{ system("unzip /path/to/archive/dec2020.zip "$4) }'