Find the answer to your Linux question:
Results 1 to 4 of 4
Is it possible to script folder creation based on a file name and then move the file itself into that folder? For example, if I have a file called 2000234.pdf, ...
  1. #1
    Just Joined!
    Join Date
    Aug 2005
    Posts
    6

    Script to organize files.

    Is it possible to script folder creation based on a file name and then move the file itself into that folder?

    For example, if I have a file called 2000234.pdf, can a script create a directory called 2000000 and move the file into that directory? Then, if the next file is something like 2000187 it will be moved into the same folder (2000000). If the third file is 2001287.pdf, the script would then create a folder named 2001000 and move the file ..1278 into it. Is this possible? What commands would I start with for working with this? Any help would be greatly appreciated.

    Thank you.

  2. #2
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by jamesman View Post
    Is it possible to script folder creation based on a file name and then move the file itself into that folder?
    yes

    For example, if I have a file called 2000234.pdf, can a script create a directory called 2000000 and move the file into that directory?
    yes

    Then, if the next file is something like 2000187 it will be moved into the same folder (2000000). If the third file is 2001287.pdf, the script would then create a folder named 2001000 and move the file ..1278 into it. Is this possible?
    yes
    What commands would I start with for working with this? Any help would be greatly appreciated.
    the mv command renames files/folders.. most importantly, get yourself a shell programing book or search unix tutorials from the internet. get yourself familiarize with shell programming.

  3. #3
    Just Joined!
    Join Date
    Aug 2007
    Posts
    37
    Code:
    for FILE in *pdf; do                  # For each pdf in the current directory...
        DIRECTORY="${FILE:0:4}000"        # Take the first 4 chars of the filename and add "000" on the end
        if ! [[ -d "$DIRECTORY" ]]; then  # If a directory of that name doesn't already exist...
            mkdir "$DIRECTORY"            # ...create it.
        fi
        mv "$FILE" "$DIRECTORY"           # then move the pdf to the appropriate directory.
    done

  4. #4
    Just Joined!
    Join Date
    Aug 2005
    Posts
    6
    Thank you very much. Also, thanks for the descriptions of each line. They help a lot in the learning process.

    The only thing left for me to do is to see if I can add some logic to make sure that the .pdf files are not "locked" or in use before being copied.

    Thanks again,

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...