Я хочу сделать резервную копию только моих музыкальных папок FLAC. Файлы FLAC могут быть вложены так же внутри папок:
AlbumName/
├── Files/
│ ├── someSong01.flac
│ ├── someSong02.flac
├── Covers/
│ ├── someCover01.jpg
│ └── someCover02.jpg
Как скопировать и переместить все папки AlbumName с их соответствующей структурой и контентом, которые содержат где-то внутри хотя бы одного файла FLAC (я буду предполагать этого достаточно, чтобы сказать: музыка находится в формате FLAC)
EDIT: файлы FLAC могут быть вложенными; поэтому я могу иметь:
AlbumName2/
├── someSong01.flac
├── someSong02.flac
├── Covers/
│ ├── someCover01.jpg
| └── someCover02.jpg
И я хочу скопировать эти папки со всем их содержимым, а не только с файлами FLAC и вставить в другой каталог.
Итак, если у меня есть well
AlbumName3/
├── someSong01.mp3
├── someSong02.mp3
├── Covers/
│ ├── someCover01.jpg
| └── someHiddenSong.flac
и
AlbumName4/
├── Files/
│ ├── someSong01.mp3
│ ├── someSong02.mp3
├── Covers/
│ ├── someCover01.jpg
│ └── someCover02.jpg
Я хочу cp рекурсивно перейти в другой каталог AlbumName, AlbumName2 и AlbumName3, но не AlbumName4
EDIT: Ни один из ответов действительно не делал то, что я хочу, поэтому в итоге я использовал что-то вроде этого:
find -mindepth 2 -name '*.flac' -exec dirname {} \; | awk -F "/" '{print $2}' | sort -u | while read -r dirname; do cp -r "$dirname" "backup/"; done
в основном я перечисляю все файлы flac, я извлекаю корневую папку с помощью awk, I удалите дубликаты, и я делаю то, что хочу
Привет, мой друг, вы можете использовать
mkdir newdirectory
cp -r --parents */*.flac newdirectory/
Ответ 1: Вы можете также использовать команду find для этого.
mkdir newDir && find AlbumName/ -iname "*.flac" -exec cp --parents "{}" newDir/ \;
Ответ 1:
mkdir создает новый каталог , find команда находит файлы *.flac, расположенные в папке AlbumName. Команда exec выполняет команду cp для каждого имени файла, возвращаемого find.
Ответ 2: Вы также можете использовать команду find с xargs
mkdir newDir && find AlbumName/ -iname "*.flac" | xargs -I{} cp --parents {} newDir/
Дополнительная информация: find, xargs
Хорошие ответы
Я хочу добавить еще один способ, вы также можете использовать комбинацию find и cpio
find . -name "*.flac" -print0|cpio --null -pdm destination/
Объяснение: GNU find searches the directory tree rooted at each given file name by evaluating the given expression from left to right, according to the rules of precedence (see Operators), until the outcome is known (the left-hand side is false for AND operations, true for OR), at which point find moves on to the next file name. GNU cpio is a tool for creating and extracting archives, or copying files from one place to another. It handles a number of cpio formats as well as reading and writing tar files. Существует 3 режима cpio: Режим копирования: In copy-out mode, cpio copies files into an archive. It reads a list of filenames, one per line, on the standard input, and writes the archive onto the standard output. Режим копирования: In copy-in mode, cpio copies files out of an archive or lists the archive contents. It reads the archive from the standard input. Режим копирования: In copy-pass mode, cpio copies files from one directory tree to another, combining the copy-out and copy-in steps without actually using an archive. It reads the list of files to copy from the standard input; the directory into which it will copy them is given as a non-option argument. Здесь мы используем режим копирования. Опции, используемые в следующей команде:Объяснение:
Режим копирования: In copy-out mode, cpio copies files into an archive. It reads a list of filenames, one per line, on the standard input, and writes the archive onto the standard output. Режим копирования: In copy-in mode, cpio copies files out of an archive or lists the archive contents. It reads the archive from the standard input. (f6) cpio: Режим копирования: In copy-out mode, cpio copies files into an archive. It reads a list of filenames, one per line, on the standard input, and writes the archive onto the standard output. '-p, - pass-through' Run in copy-pass mode. see ``Copy-pass mode``. Режим копирования: In copy-in mode, cpio copies files out of an archive or lists the archive contents. It reads the archive from the standard input. --quiet' Не печатайте количество скопированных блоков. `GNU find searches the directory tree rooted at each given file name by evaluating the given expression from left to right, according to the rules of precedence (see Operators), until the outcome is known (the left-hand side is false for AND operations, true for OR), at which point find moves on to the next file name.
find:
cpio: [ ! d25]
Опция заключается в использовании rsync, который копирует только файлы flac и сохраняет структуру каталогов:
rsync -avzm --include=*/ --include=*.flac --exclude=* albums/ backup/
архив v verbose z compress во время передачи (возможно, не полезно копировать на том же компьютере) m prune empty dirs first include включает в себя все каталоги second include включает в себя flac-файлы exclude исключает все другие файлы Просто мне пришлось решить ту же проблему для моей музыкальной библиотеки и решить ее с помощью следующего адаптированного сценария. Я не полностью его программировал с помощью переменных, так как я только один раз их буду использовать:).
Сценарий перемещает каждый каталог, содержащий файлы flac, включая все другие файлы и подкаталоги, в новое место с помощью rsync. rsync позволяет возобновить скрипт, если он остановится во время процесса.
Моя структура библиотеки:
library
|-artist
|- album 1 (mp3)
|- album 2 (flac)
Новая структура библиотеки:
library
|-artist
|- album 1 (mp3)
library-lossless
|-artist
|- album 2 (flac)
(1) запустите следующий сценарий оболочки в пункте назначения SOURCE (замените TARGET с соответствующим каталогом по вашему выбору - я просто использовал абсолютный путь)
строка 1: найти все каталоги, содержащие flac-файлы и pipe (|), которые в строке сортировки 2: удалить дубликаты с сортировкой и трубкой, список в строку цикла do 3: для каждой директории выполните строку 4: покажите каталог в строке процесса 5: rsync в целевой каталог плюс удалите источник и сохраните структуру (-R) в целевом местоположении. строка 6: удалите пустую директорию (только как rsync удаляет файлы)
find . -type f -name \*.flac -printf "%h\n" |
sort -u |
while read -r dirname; do
echo $dirname
rsync -azvm -R --remove-source-files "${dirname}" TARGET
find "${dirname}" -type d -delete
done
(2) после успешного выполнения скрипта в (1) вы можете выполнить следующую команду в исходном каталоге
find . -depth -type d -empty -delete
Эта команда удаляет все пустое каталоги, не удаленные в скрипте. То есть Каталоги «Artist», где все подпапки / альбомы включали файлы flac.
Привет, мой друг, вы можете использовать
mkdir newdirectory
cp -r --parents */*.flac newdirectory/
Ответ 1: Вы можете также использовать команду find для этого.
mkdir newDir && find AlbumName/ -iname "*.flac" -exec cp --parents "{}" newDir/ \;
Ответ 1:
mkdir создает новый каталог , find команда находит файлы *.flac, расположенные в папке AlbumName. Команда exec выполняет команду cp для каждого имени файла, возвращаемого find.
Ответ 2: Вы также можете использовать команду find с xargs
mkdir newDir && find AlbumName/ -iname "*.flac" | xargs -I{} cp --parents {} newDir/
Дополнительная информация: find, xargs
Хорошие ответы
Я хочу добавить еще один способ, вы также можете использовать комбинацию find и cpio
find . -name "*.flac" -print0|cpio --null -pdm destination/
Объяснение: GNU find searches the directory tree rooted at each given file name by evaluating the given expression from left to right, according to the rules of precedence (see Operators), until the outcome is known (the left-hand side is false for AND operations, true for OR), at which point find moves on to the next file name. GNU cpio is a tool for creating and extracting archives, or copying files from one place to another. It handles a number of cpio formats as well as reading and writing tar files. Существует 3 режима cpio: Режим копирования: In copy-out mode, cpio copies files into an archive. It reads a list of filenames, one per line, on the standard input, and writes the archive onto the standard output. Режим копирования: In copy-in mode, cpio copies files out of an archive or lists the archive contents. It reads the archive from the standard input. Режим копирования: In copy-pass mode, cpio copies files from one directory tree to another, combining the copy-out and copy-in steps without actually using an archive. It reads the list of files to copy from the standard input; the directory into which it will copy them is given as a non-option argument. Здесь мы используем режим копирования. Опции, используемые в следующей команде:Объяснение:
Режим копирования: In copy-out mode, cpio copies files into an archive. It reads a list of filenames, one per line, on the standard input, and writes the archive onto the standard output. Режим копирования: In copy-in mode, cpio copies files out of an archive or lists the archive contents. It reads the archive from the standard input. (f6) cpio: Режим копирования: In copy-out mode, cpio copies files into an archive. It reads a list of filenames, one per line, on the standard input, and writes the archive onto the standard output. '-p, - pass-through' Run in copy-pass mode. see ``Copy-pass mode``. Режим копирования: In copy-in mode, cpio copies files out of an archive or lists the archive contents. It reads the archive from the standard input. --quiet' Не печатайте количество скопированных блоков. `GNU find searches the directory tree rooted at each given file name by evaluating the given expression from left to right, according to the rules of precedence (see Operators), until the outcome is known (the left-hand side is false for AND operations, true for OR), at which point find moves on to the next file name.
find:
cpio: [ ! d25]
Опция заключается в использовании rsync, который копирует только файлы flac и сохраняет структуру каталогов:
rsync -avzm --include=*/ --include=*.flac --exclude=* albums/ backup/
архив v verbose z compress во время передачи (возможно, не полезно копировать на том же компьютере) m prune empty dirs first include включает в себя все каталоги second include включает в себя flac-файлы exclude исключает все другие файлы Просто мне пришлось решить ту же проблему для моей музыкальной библиотеки и решить ее с помощью следующего адаптированного сценария. Я не полностью его программировал с помощью переменных, так как я только один раз их буду использовать:).
Сценарий перемещает каждый каталог, содержащий файлы flac, включая все другие файлы и подкаталоги, в новое место с помощью rsync. rsync позволяет возобновить скрипт, если он остановится во время процесса.
Моя структура библиотеки:
library
|-artist
|- album 1 (mp3)
|- album 2 (flac)
Новая структура библиотеки:
library
|-artist
|- album 1 (mp3)
library-lossless
|-artist
|- album 2 (flac)
(1) запустите следующий сценарий оболочки в пункте назначения SOURCE (замените TARGET с соответствующим каталогом по вашему выбору - я просто использовал абсолютный путь)
строка 1: найти все каталоги, содержащие flac-файлы и pipe (|), которые в строке сортировки 2: удалить дубликаты с сортировкой и трубкой, список в строку цикла do 3: для каждой директории выполните строку 4: покажите каталог в строке процесса 5: rsync в целевой каталог плюс удалите источник и сохраните структуру (-R) в целевом местоположении. строка 6: удалите пустую директорию (только как rsync удаляет файлы)
find . -type f -name \*.flac -printf "%h\n" |
sort -u |
while read -r dirname; do
echo $dirname
rsync -azvm -R --remove-source-files "${dirname}" TARGET
find "${dirname}" -type d -delete
done
(2) после успешного выполнения скрипта в (1) вы можете выполнить следующую команду в исходном каталоге
find . -depth -type d -empty -delete
Эта команда удаляет все пустое каталоги, не удаленные в скрипте. То есть Каталоги «Artist», где все подпапки / альбомы включали файлы flac.