Home > Back-end >  How to make a FOR loop to move files to directory based on file extension
How to make a FOR loop to move files to directory based on file extension

Time:11-15

Im trying to sort thousands of files and put them in their own folder based on file extension. For example, JPG files to go into a JPG folder.

How can I create a for loop to address this?

What I have attempted to far:

# This listed out all the file extensions and the count for each extension:
find . -type f | rev | cut -d. -f1 | rev  | tr '[:upper:]' '[:lower:]' | sort | uniq --count | sort -rn
#This was able to find all jpegs in the media folder
find /media -iname '*.jpg' 
# This worked, however the MV command does not create the folder
find /media -iname '*.jpg' -exec mv '{}' /media/genesis/Passport/consolidated/jpg/ \; # 

Im guessing that the for loop would be something like but I cant seem to figure it out:

for dir in 'find /media -iname "*.jpg"'; do
    mkdir $dir;
    mv $dir/*;
done

CodePudding user response:

You can try this script.

It should find all files within /media and move it to a directory with a similar extension in your pwd.

$ cat locate.sh
#!/usr/bin/env bash

for files in $(find /media -type f); do 
    dir=$(echo "$files" | sed 's/.[^.]*.\(.*\)/\1/g')  
    loc_path=$(pwd)/"$dir" 
    if [[ ! -d "$loc_path" ]]; then 
        mkdir "$loc_path" &>/dev/null 
        mv "$files" "$loc_path"
    else
        mv "$files" "$loc_path"
    fi
done

NOTE: Please test before using on actual data.

CodePudding user response:

To find all the files of a particular extension and move then to a destination we can use find command as follows:

find . -name "*.jpg" -exec mv {} $destination/ \;

This being the critical logic, you can just create a for loop on top of this to iterate through all the known file extensions in your media folder

## List all the known extensions in your media folder.
declare -a arr=("jpg" "png" "svg")

## Refer question 1842254 to get all the extentsions in your folder.
## find . -type f | perl -ne 'print $1 if m/\.([^.\/] )$/' | sort -u


## now loop through the above array
for i in "${arr[@]}"
do
   echo "$i"
   ## Create a directory based on file extension
   destination="$i"
   mkdir $destination
   find /media -iname "*.$i" -exec mv {} $destination/ \;
done

Note that you can change your destination to be whatever you want. I just left it in the same directory.

Here is an executable shell script for your reference: https://onlinegdb.com/NEQSpojhM

  • Related