Ubuntu – How to copy all folders that contain a specific file

command line

I want to backup only my FLAC music folders. FLAC files could be nested like that inside the folders:

├── Files/
│   ├── someSong01.flac
│   ├── someSong02.flac
├── Covers/
│   ├── someCover01.jpg
│   └── someCover02.jpg

How do I copy and move all AlbumName's folders with their corresponding structure and content that contain somewhere inside at least one FLAC file (I'll assume this is enough to say: the music is in FLAC format)

FLAC files could be nested; so I can have:

├── someSong01.flac
├── someSong02.flac
├── Covers/
│   ├── someCover01.jpg
|   └── someCover02.jpg

And I want to copy those folders with all their contents, not only FLAC files, and paste to another directory.

So if I have as well

├── someSong01.mp3
├── someSong02.mp3
├── Covers/
│   ├── someCover01.jpg
|   └── someHiddenSong.flac


├── Files/
│   ├── someSong01.mp3
│   ├── someSong02.mp3
├── Covers/
│   ├── someCover01.jpg
│   └── someCover02.jpg

I want to cp recursively to another directory AlbumName, AlbumName2 and AlbumName3 but not AlbumName4

None of the answers were really doing what I want, so I ended up using something like that:

 find -mindepth 2 -name '*.flac' -exec dirname {} \; | awk -F "/" '{print $2}' | sort -u | while read -r dirname; do cp -r "$dirname" "backup/"; done

basically I list all flac files, I retrieve the root folder using awk, I delete the duplicates and I do what I want

Best Answer

An option is to use rsync, which copies only flac files and preserves directory structure:

rsync -avzm --include=*/ --include=*.flac --exclude=* albums/ backup/
  • a archive
  • v verbose
  • z compress during transfer (may not be useful copying on the same computer)
  • m prune empty dirs
  • first include includes all directories
  • second include includes flac files
  • the last exclude excludes all other files
Related Question