Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Move files based on first letter of name

Tags:

bash

I have a large amount of files which I am trying to organize into three folders alphabetically. I'm trying to get a bash script together which has the ability to get the first letter of the file, then move it into a folder based on that first letter.

For example:

file -> folder name

apples -> A-G

banana -> A-G

tomato -> H-T

zebra -> U-Z

Any tips would be appreciated! TIA!

like image 362
user1247483 Avatar asked May 22 '12 00:05

user1247483


1 Answers

#!/bin/bash
dirs=(A-G H-T U-Z)
shopt -s nocasematch

for file in *
do
    for dir in "${dirs[@]}"
    do
        if [[ $file =~ ^[$dir] ]]
        then
            mv "$file" "$dir"
            break
        fi
    done
done
like image 190
Dennis Williamson Avatar answered Sep 30 '22 05:09

Dennis Williamson