Move files to directory based on file name

15 October 2020

I have a folder with files with file names that look like this:

zz_W4mIV_5Swi6-h9uHDQQgOB_XRR3247668M846325_CTLR.jpg
zz_vd2Ef2Of_g6iomLM_QyE3A_74D139NWD81747416_FTXNOO.jpg
zz_DBoTkZl51HgzVuNnJ7YyQN_74D139NWD81747416_CTLR.jpg

My goal is to move the files into folders based on the part in the file name that is XRR3247668M846325 and 74D139NWD81747416 in the example above. The first file should be moved to a folder called XRR3247668M846325, the other two files to a folder called 74D139NWD81747416.

On macOS, the following shell command works well:

for file in *; do dir=$(echo $file | cut -c 27-43); mkdir -p $dir; mv $file $dir; done

For each file in the current directory

  • Extract the directory name dir from the file name by taking the 27th to 43rd characters of the file name with cut -c 27-43
  • Create the directory (if it does not exist yet) with mkdir -p $dir
  • Move the file to the associated directory with mv $file $dir

You can download a bash script with the above command from GitHub.

To use it, cd into the directory with your files and execute

/path/to/move-files-to-new-directory-based-on-file-name.sh <start> <end>

<start> and <end> are the positions of the first and last character of the directory name as it is used in the file name. To use the character sequence from the 27th to the 43rd character in the file name as the new directory name, execute

/path/to/move-files-to-new-directory-based-on-file-name.sh 27 43