moving files to different directories

im trying to move media and other files which are in a specified directory to another directory and create another one if it does not exits(where the files will go),them also create a directory will the remaining files with different extensions will go.my first problem is that my script is not making a new directory and it is not moving the files to other directories and what code can i use to move files with different extensions to one directory? this is what i have had so far,correct me where im wrong and help modify my script

#!/bin/bash
From=/home/katy/doc
To=/home/katy/mo #directory where the media files will go
WA=/home/katy/do # directory where the other files will go
 if [ ! -d "$To" ]; then
   mkdir -p "$To"
 fi
cd $From
find path -type f -name"*.mp4" -exec mv {} $To \;

I don't see any issue with your directory creation code... You sure the directory "/home/katy/mo" is not getting created?... Check again... May be there is a problem with the permission... Hope you are running the code with root or with user katy, looks like the home directory of user katy...

Your find command is also fine just that there is no space between -name and "*.mp4", might be a typo though... Check those and let us know...

--ahamed

thanks it was just a typo error though im stack how can i move other files with different extension to another directory?

Use the same command with ! -name "*.mp4" and it should do the trick!...

--ahamed

but how do i group them for example i have .txt,.doc,.pdf

You wanted *.mp4 and the remaining right?...

--ahamed

yes but i want to know how to use the same command, lets say i wanted to move media files,.mp3,.mp4,.avi to same directory and the rest ofthe files i can use
the command mv *

find path \( -name "*.mp3" -o -name "*.mp4" \) -exec... something like this?

--ahamed

Another approach could be something like the following

#!/bin/bash

[[ -d ./pngdir ]] || mkdir -p ./pngdir
[[ -d ./jpgdir ]] || mkdir -p ./jpgdir
[[ -d ./others ]] || mkdir -p ./others

for file in *
do
   [[ -f $file ]] || continue
   case ${file##*.} in
      mp4)  echo "mv $file to mg4 directory" ;;
      png)  echo "mv $file to png directory" ;;
      jpg)  echo "mv $file to jpg directory" ;;
        *)  echo "mv $file to others directory" ;;
   esac
done
1 Like