Home > database >  recursively move all files in each sub-subdirectory up one level
recursively move all files in each sub-subdirectory up one level

Time:02-16

If I have this file structure:

headir/
 A/ABD/<files to be moved>
 B/DSUH/<files to be moved>
 .
 .
 .

On linux (I'm using Ubuntu) how do I move all files out of each lowest level sub-directories so it looks like:

headir/
 A/<files to be moved>
 B/<files to be moved>
 .
 .
 .

i.e. sub-directories ABD, DSUH etc are all redundant.

Thanks!

CodePudding user response:

Perhaps something like:

while read d; do
    mv "$d/*/*" "$d/"
done < <(ls -1 headdir)

CodePudding user response:

This Shellcheck-clean code should do what you want if it is run in the top-level directory (headir):

#! /bin/bash -p

shopt -s nullglob
shopt -s dotglob

for subsub in */*; do
    [[ -L $subsub ]] && continue    # Skip symlinks
    [[ -d $subsub ]] || continue    # Skip non-directories

    sub=${subsub%/*}
    for file in "$subsub"/*; do
        printf "Moving '%s' to '%s'\\n" "$file" "$sub" >&2
        mv -- "$file" "$sub"
    done
    printf "Removing directory '%s'\\n" "$subsub" >&2
    rmdir -- "$subsub"
done

Make sure that you understand it and try it on a copy of the directory (or a similarly-structured test directory) before using it for real.

  • Related