I have hundreds of thousands of files in hundreds of directories.

An example directory structure is


For folders that have 'bar' directories, I want to move contents to following structure.


Can this be accomplished using find and mv?

  • 2
    are the foo and bar directorys always in the same depth? – pLumo Jan 8 at 14:12
  • Yes, the depth is consistent. – Umer Jan 8 at 14:18

Some little script to achieve this:

# Set the variables

# let * match hidden files
shopt -s dotglob

# Loop through find (which is declared after done)
while IFS= read -r dir; do

    # Read names of foo dir
    foo=$(printf '%s' "$dir" | cut -d'/' -f $foo_depth)

    # mkdir target and mv dir there
    mkdir -p "$target"
    mv "$dir"/* "$target"

    # as you mv the content of bar dir only,
    # you may want to remove the full path to that folder
    # rmdir -p will do that without deleting anything that is not empty,
    # we can ignore the "failed to remove" messages.
    [ $? = 0 ] && rmdir -p "${dir}"

done < <(find "$main" -type d -name "$bar_name")

# Turn off dotglob
shopt -u dotglob
  • Thanks but my apologies since I messed up a bit. The 'sub' directory is not alone there and is a mix of files and folders that I intend to move. I've edited the question. Can you please edit your script? Really appreciated. – Umer Jan 9 at 7:39
  • I made an update. – pLumo Jan 9 at 8:43

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.