Search code examples
linuxfindmv

What is the linux command to move the files of subdirecties into one level up respectively


The path structure of the files on my server is similar to that shown below,

/home/sun/sdir1/mp4/file.mp4 /home/sun/collection/sdir2/mp4/file.mp4

I would like to move the files of "mp4" into one level up(into sdir1 and sdir2 respectively)

So the output should be,

/home/sun/sdir1/file.mp4 /home/sun/collection/sdir2/file.mp4

I have no idea to do this, so not tried yet anything...


Solution

  • There are different ways to solve your problem

    1. If you just want to move those specific files, run these commands:

      cd /home/sun/
      mv sdir1/mp4/file.mp4 sdir1/
      mv sdir2/mp4/file.mp4 sdir2/
      
    2. If you want to move all mp4 files on those directories (sdir1 and sdir2), run these commands:

      cd /home/sun/
      mv sdir1/mp4/*.mp4 sdir1/
      mv sdir2/mp4/*.mp4 sdir2/
      

    Edit:

    1. Make a script that iterates all the directories:

    Create a script and name it and edit it with your favorite editor (nano, vim, gedit, ...):

    gedit folderIterator.sh
    

    The script file content is:

    #/bin/bash
    
    # Go to the desired directory
    cd /home/sun/
    
    # Do an action over all the subdirectories in the folder
    for dir in /home/sun/*/
    do
        dir=${dir%*/}
        mv "$dir"/mp4/*.mp4 "$dir"/
    
        # If you want to remove the subdirectory after moving the files, uncomment the following line
        # rm -rf "$dir"
    done
    

    Save the file and give it execute permissions:

    chmod +x folderIterator.sh
    

    And execute it:

    ./folderIterator.sh