Home > database >  Is there any way to zip files ignoring some names of the folders?
Is there any way to zip files ignoring some names of the folders?

Time:03-27

I want to zip some PDFs. Right now they are in:

FolderA
├── 2022
│   ├── March
│   │   ├── PDF1 
│   │   ├── PDF2 
│   │   ├── PDF3
FolderB
├── 2022
│   ├── March
│   │   ├── PDF4 
│   │   ├── PDF5 

I want my ZIP file to follow this structure:

zipname.zip
├── FolderA
│   ├── PDF1 
│   ├── PDF2 
│   ├── PDF3
├── FolderB
│   ├── PDF4
│   ├── PDF5

Is there any way to do this? So far, I found how to do it including the whole path or without any path at all (just the PDFs).

EDIT:

#!/bin/bash
echo What month do you want?
read month
mkdir "$month" || exit 1
cp -a FolderA/2022/"$month" "$month"/FolderA/
cp -a FolderB/2022/"$month" "$month"/FolderB/
zip -r $month$(date  %Y).zip "$month"/
rm -rf tmp

CodePudding user response:

By using a short script you could create a temporary directory structure before compressing the files:

#!/bin/bash
mkdir tmp || exit 1
cp -a Folder* tmp/
cd tmp || exit 1
pwd
for dir in *
do
    cd $dir
    find . -type f -iname "*.pdf" -not -name "$dir" -exec mv {} ./ \;
    find . -type d -exec rm -rf {} \;
    cd ..
done
cd ..
zip -r pdf.zip tmp/*
rm -rf tmp

Note that the -exec rm -rf {} part of find should be relatively safe, due to the script exiting if creating or changing to the tmp directory fails.

CodePudding user response:

With GNU tar:

tar -cvf pdf.tar Folder*/2022/March/* --transform 's|2022/March/||' --show-transformed-names

Output:

FolderA/PDF1
FolderA/PDF2
FolderA/PDF3
FolderB/PDF4
FolderB/PDF5

--transform uses sed's syntax from its s command to search and replace in path and filename.

  • Related