Search code examples
bashunixfilesystemssubdirectoryfile-move

How to move files from subfolders to their parent directory (unix, terminal)


I have a folder structure like this: A big parent folder named Photos. This folder contains 900+ subfolders named a_000, a_001, a_002 etc.

Each of those subfolders contain more subfolders, named dir_001, dir_002 etc. And each of those subfolders contain lots of pictures (with unique names).

I want to move all these pictures contained in the subdirectories of a_xxx inside a_xxx. (where xxx could be 001, 002 etc)

After looking in similar questions around, this is the closest solution I came up with:

for file in *; do
  if [ -d $file ]; then
    cd $file; mv * ./; cd ..; 
  fi
done

Another solution I got is doing a bash script:

#!/bin/bash
dir1="/path/to/photos/"
subs= `ls $dir1`

for i in $subs; do
  mv $dir1/$i/*/* $dir1/$i/ 
done

Still, I'm missing something, can you help?

(Then it would be nice to discard the empty dir_yyy, but not much of a problem at the moment)


Solution

  • You could try the following bash script :

    #!/bin/bash
    
    #needed in case we have empty folders
    shopt -s nullglob
    
    #we must write the full path here (no ~ character)
    target="/path/to/photos"
    
    #we use a glob to list the folders. parsing the output of ls is baaaaaaaddd !!!!
    #for every folder in our photo folder ... 
    for dir in "$target"/*/
    do
        #we list the subdirectories ...
        for sub in "$dir"/*/
        do
            #and we move the content of the subdirectories to the parent
            mv "$sub"/* "$dir"
            #if you want to remove subdirectories once the copy is done, uncoment the next line
            #rm -r "$sub"
        done
    done
    

    Here is why you don't parse ls in bash