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):


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

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

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")'
  • what is 1 in your find command?
    – pLumo
    Commented Feb 4, 2022 at 8:13
  • i run the code in the working dir, so can be find * or find . Commented Feb 4, 2022 at 9:35

1 Answer 1


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 '
    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.

  • 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? Commented Feb 4, 2022 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) Commented Feb 4, 2022 at 13:00
  • ah right, because the first parent dir is different!
    – pLumo
    Commented Feb 4, 2022 at 13:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .