Bash – Move Files into Subdirectories Based on Filename Prefix

bashfilesshell

I have a directory that contains quite a lot of files with names made up of 8 random letters, numbers, _ and -, e.g.:

0dckGYH5.jpg
32Pz5-WQ.png
32_17pxH.png
Hsf4BQW9.jpg
xh-fa3Nu.gif
zYtBEaKA.png
...

Now the task is to go through each of the files, create a directory named after the first 2 characters of the file's name, and move the file into that directory.

The final structure should look like this:

0d
└── 0dckGYH5.jpg
32
├── 32Pz5-WQ.png
└── 32_17pxH.png
Hs
└── Hsf4BQW9.jpg
xh
└── xh-fa3Nu.gif
zY
└── zYtBEaKA.png

Since I don't have permission to install anything on the system, how would I go about doing this with only basic shell commands?

Best Answer

A straightforward combination of mkdir -p and mv should be enough

for f in *; do d="${f:0:2}"; mkdir -p "$d"; mv -t "$d" -- "$f"; done

Demonstrating:

$ ls
0dckGYH5.jpg  32_17pxH.png  32Pz5-WQ.png  Hsf4BQW9.jpg  xh-fa3Nu.gif  zYtBEaKA.png

$ for f in *; do d="${f:0:2}"; mkdir -p "$d"; mv -t "$d" -- "$f"; done

$ tree .
.
├── 0d
│   └── 0dckGYH5.jpg
├── 32
│   ├── 32_17pxH.png
│   └── 32Pz5-WQ.png
├── Hs
│   └── Hsf4BQW9.jpg
├── xh
│   └── xh-fa3Nu.gif
└── zY
    └── zYtBEaKA.png

5 directories, 6 files

If your system's version of mkdir doesn't have the -p option, then you can test for the directory's existence explicitly e.g.

 for f in *; do d="${f:0:2}"; [[ -d "$d" ]] || mkdir "$d"; mv -t "$d" -- "$f"; done
Related Question