1

Goal: Append (rename) and move only those files whose path contains a specific directory name, at any level.

Extracting files from trees based on directory names. From years of periodic mobile backup, trying to extract (move) those files that are inside of directories where any of the parent directories match a name on a custom "media directory list". Append the full path as a prefix for each file and place appeneded files into a single OUTPUT dir. (Using file extension as a selector would not work for my purposes, must be one of the parent dir name.) For example,

Input dirs (each with many subdirs):

20011231-bkp-1
20021231-bkp-2
20031231-bkp-3

Output (appended files in a single "OUTPUT" dir):

20011231-bkp-1__dir-a__dir-b__dir-c__WhatsApp Images__imag-1.jpg
20021231-bkp-2__dir-a__dir-b__dir-c__WhatsApp Images__Sent__imag-1.jpg
20031231-bkp-3__dir-a__Camera__imag-1.mp4
20031231-bkp-3__dir-a__Camera__dir-x__imag-1.mp4

media dir list (these dirs can be anywhere in the path, note spaces). Rename and move only but all files within these, exact match, recursively:

WhatsApp Images
WhatsApp Audio
Recorders
Camera

This works for appending and moving, but have trouble restricting only to those files that are inside the "media dir list":

find 1 -type f| perl -ne 'chop;$from=$_;$to=$_;$to=~s/\//__/g;system("echo mv $from $to")'
2
  • what is 1 in your find command?
    – pLumo
    Feb 4 at 8:13
  • i run the code in the working dir, so can be find * or find . Feb 4 at 9:35

1 Answer 1

0

I'd use find -path "..." -exec bash -c '...':

find *-bkp-* \
  \( \
    -path "*/WhatsApp Images/*" \
    -or -path "*/WhatsApp Audio/*" \
    -or -path "*/Recorders/*" \
    -or -path "*/Camera/*" \
  \) \
  -exec bash -c '
    OUTPUT_DIR="OUTPUT"
    mkdir -p "$OUTPUT_DIR"
    for f in "$@"; do mv -v "$f" "$OUTPUT_DIR/${f//\//_}"; done
  ' find-sh {} +

You might want to add a flag to control what should happen with existing files, e.g. -n to not overwrite existing files -f to force overwrite or -b to backup existing files.

3
  • nice! an issue: files in subdirs of the media dir list (eg, /Recorders/Sony/1/), are not appended but only moved with the tree to OUTPUT. the media dirs can be anywhere in a long path, all recursive files need to be renamed and moved. idea to fix? Feb 4 at 9:21
  • yes, there are dups in the input dir trees. those should not trouble here as appending the path to the filename, then moving to OUTPUT will result in only unique filenames in OUTPUT. (dups eliminated in a separate, later step) Feb 4 at 13:00
  • ah right, because the first parent dir is different!
    – pLumo
    Feb 4 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.