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

3.4k Views Asked by At

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

4

There are 4 best solutions below

2
On BEST ANSWER

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
0
On

You can do this:

# move all .mp4 files from sdir1/mp4 to sdir1 directory
user@host:~/home/sun$ mv sdir1/mp4/*.mp4 sdir/

# move all .mp4 files from collection/sdir2/mp4 to collection/sdir2 directory
user@host:~/home/sun$ mv collection/sdir2/mp4/*.mp4 collection/sdir2/

# move only 1 file
user@host:~/home/sun$ mv sdir1/mp4/file.mp4 sdir/
user@host:~/home/sun$ mv collection/sdir2/mp4/file.mp4 collection/sdir2/
0
On

I suggest you use find and something like

cd /home/sun/sdir1/mp4/
find . -name "*" -exec mv {} /home/sun/sdir1/ \;
cd /home/sun/collection/sdir2/mp4/
find . -name "*" -exec mv {} /home/sun/collection/sdir2/ \;

Alternatively, you could use tar and something like

cd /home/sun/sdir1/mp4/
tar cfp - * | (cd ../ ; tar xvvf -)
# Make sure everything looks good
rm -rf mp4
cd /home/sun/collection/sdir2/mp4/
tar cfp - * | (cd ../ ; tar xvvf -)
# Make sure everything looks good
rm -rf mp4
0
On

The command to move a file (or directory) up one level is:

mv /home/sun/sdir1/mp4/file.mp4 ..

Wildcards can be used to select more files & directories, you can also provide more than one directory at a time.

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