Skip to content

Instantly share code, notes, and snippets.

@parmentf
Last active December 2, 2019 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parmentf/93788f0fb83298d0116283c6ac452957 to your computer and use it in GitHub Desktop.
Save parmentf/93788f0fb83298d0116283c6ac452957 to your computer and use it in GitHub Desktop.
carottage

Carottage

Ce script est destiné à extraire d'un .zip contenant un répertoire contenant des fichiers à plat (XML, ou JSON par exemple) un certain nombre de fichiers d'exemple, pris au hasard, rassemblés dans un fichier .zip avec la même structure.

Structure du fichier d'entrée

$ unzip -l crossref-2017.zip
Archive:  crossref-2017.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2019-01-30 14:12   2017/
     6874  2019-01-30 13:31   2017/10.1016_j.bulcan.2017.05.002.xml
     3673  2019-01-30 12:43   2017/10.2217_fon-2016-0441.xml
     2931  2019-01-30 13:57   2017/10.1016_j.actpha.2017.07.001.xml
    18155  2019-01-30 13:29   2017/10.1084_jem.20170229.xml
...
    10096  2019-01-30 12:42   2017/10.1093_jac_dkw437.xml
     2318  2019-01-30 14:05   2017/10.4000_insitu.15606.xml
    35323  2019-01-30 14:01   2017/10.1186_s12885-017-3794-3.xml
    19636  2019-01-30 13:58   2017/10.1073_pnas.1703790114.xml
---------                     -------
1604000585                     93072 files

Usage

$ ./carottage.sh crossref-2017.zip 500
Création de crossref-2017_500_extrait.zip
$ ll -h
total 278M
drwxr-xr-x 2 parmentf parmentf 4,0K nov.  29 17:20 ./
drwxr-xr-x 3 parmentf parmentf 4,0K nov.  29 11:33 ../
-rwxr-xr-x 1 parmentf parmentf  734 nov.  29 17:19 carottage.sh*
-rw-r--r-- 1 parmentf parmentf 1,5M nov.  29 17:20 crossref-2017_500_extrait.zip
-rw-r--r-- 1 parmentf parmentf 277M févr.  4  2019 crossref-2017.zip

⚠️ La création du fichier nécessite la création des fichiers à y mettre, et donc utilise la place nécessaire aux fichiers décompressés.

#!/usr/bin/env bash
if [ $# -ne 2 ];
then
echo "Mauvais nombre d'arguments."
echo "Usage: ${0} fichier.zip nbFichiersÀExtraire"
echo " Le fichier zip doit contenir un répertoire."
exit 1
fi
input="$1"
nb="${2:-10}"
files=$(
unzip -l "$input" | \
tail +5 | \
grep -v '\-\-\-\-' | \
grep -v ' files' | \
shuf -n "$nb" | \
cut -c31- | \
xargs echo # trim filenames and put them on one line
)
for file in $files
do
unzip -q "$input" "$file"
done
outputdir=$(
echo "$files" | \
cut -d'/' -f1
)
outputfile="${input//.zip/_${nb}_extrait.zip}"
zip -qr "$outputfile" "$outputdir"
rm -rf "$outputdir"
echo "Création de ${outputfile}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment