user1247483
user1247483

Reputation: 55

Bash: Move files based on first letter of name

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!

Upvotes: 5

Views: 3655

Answers (3)

Andy D
Andy D

Reputation: 916

Adding my code - this is 99% based on Dennis Williamson - I just added an if block to make sure you are not moving a dir into a target dir, and I wanted a dir per letter.

#!/bin/bash
dirs=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
shopt -s nocasematch

for file in *
do
    for dir in "${dirs[@]}"
    do

     if [ -d "$file" ]; then
      echo 'this is a dir, skipping'
      break
     else
      if [[ $file =~ ^[$dir] ]]; then
       echo "----> $file moves into -> $dir <----"
       mv "$file" "$dir"
       break
      fi
     fi
  done
done

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 359935

#!/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

Upvotes: 6

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

You want substring expansion and a case statement. For example:

thing=apples
case ${thing:0:1} in
    [a-gA-G]) echo "Do something with ${thing}." ;;
esac

Upvotes: 2

Related Questions