Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move files to directories based on first part of filename?

Tags:

bash

filenames

I have several thousand ebooks that need to be organized on a headless linux server running bash through SSH. All of the ebooks are thankfully named with one of 2 conventions.

  • AuthorFirstName AuthorLastName - Book Title.pdf
  • AuthorFirstName AuthorLastName - Book Series #inSeries - Book Title.pdf

What I would like to do is to move all of the books into an organized system such as:

`DestinationDirectory/FirstLetterOfAuthorFirstName/Author Full Name/pdf's`

e.g. the following books

Andrew Weiner - Changes.pdf 
Allan Cole - Timura Trilogy 01 - When the Gods Slept.pdf

should be placed in the following folders

/books/A/Allan Cole/Allan Cole - Timura Trilogy 01 - When the Gods Slept.pdf
/books/A/Andrew Weiner/Andrew Weiner - Changes.pdf

I need help with how to put this all into a bash script that will grab the filenames of all the PDF files in the current directory, and then move the files to the proper directory, creating the directory if it doesn't already exist.

like image 925
Aevum Decessus Avatar asked Aug 09 '09 18:08

Aevum Decessus


People also ask

How do I move a file with a specific name in Linux?

Moving and Renaming files on Linux A file can be renamed during a move process using the mv command. You simply give the target path a different name. When mv moves the file, it will be given a new name. For example, to move a file named student1.

How do I move a file to a different directory?

Right-click the file or folder you want, and from the menu that displays click Move or Copy. The Move or Copy window opens. Scroll down if necessary to find the destination folder you want.

What command is used to move files and directories?

mv command is used to move files and directories.


1 Answers

for f in *.pdf; do
    name=`echo "$f"|sed 's/ -.*//'`
    letter=`echo "$name"|cut -c1`
    dir="DestinationDirectory/$letter/$name"
    mkdir -p "$dir"
    mv "$f" "$dir"
done
like image 194
chaos Avatar answered Sep 28 '22 10:09

chaos