Move files to directory based on file name

15 October 2020

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


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/ <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/ 27 43