Search code examples
shellfilenamesdelimiterorganizationsubdirectory

Using BASH to Organize Files Using "_" Delimiter in File Name


I feel like what I want to do is simple enough, but I'm a novice at shell scripting so I'd appreciate any help you can give me.

QUESTION: I have a folder of files of various file types (i.e. ".jpg", ".psd", ".png") and need to organize these files into subdirectories. The file names of each file follow the same convention: "number_name.extension". Several files share the same "number" value, and what I want the script to do is create a folder with the "number" value (if it doesn't exist already) and move all files with the same "number" value into said folder regardless of file type/extension.

I know this is possible with Bourne, but I'm having trouble wrapping my head around it. I've searched around for similar threads, but nothing seems to satisfy all conditions in my question. Any assistance will be very much appreciated!


Solution

  • How about:

    for f in *; do mkdir -p ${f%%_*}; mv $f ${f%%_*}; done
    

    That will retain the full filename, but perhaps you want to trim the numbers:

    for f in *; do 
      dir=${f%%_*}
      mkdir -p $dir
      mv $f $dir/${f#*_} 
    done