1

I have a huge collection of images and I would like to put them in folders matching their first 3 charachers+.jpg extension.

So i would like to grab 4_1_0002.png file (all the files starting with 4_1) and put it in the 4_1_.jpg folder. Similarly I would like to grab 4_2_0002.png file (all the files starting with 4_2) and put it in the 4_2_.jpg folder.

All those files that I would like to sort are now in one huge folder. I expected to use a find command, but I don't know how to extract the first three characters from {} expansion parameter.

find . -type f -ok echo mv {} "path/first3char.jpg" \;

enter image description here

enter image description here

2
  • Just curious, why do you want to put .png files in a folder with a .jpg extension, why not a folder with a .png extension? Apr 1, 2017 at 14:07
  • At first I was working with jpg's, but than switched to pngs. Didnt bother to change the name
    – sanjihan
    Apr 1, 2017 at 14:56

1 Answer 1

3

Assuming that all your files are in the same directory and the filenames are reasonable sane, something like

 find . -maxdepth 1 -type f -name '*png' |
     while read line; do
         echo mv "$line" "path/${line:2:3}.jpg/"
     done

Run the command first as written (including the echo) to check whether the result makes sense. Then remove the echo and rerun.

2
  • While I did up-vote the answer, nonetheless I'd add a condition in the form of testing the directory exists, e.g., [[ -d path/${line:2:3}.jpg ]], and use it like, e.g., find . -maxdepth 1 -type f -name '*png' | while read line; do [[ -d path/${line:2:3}.jpg ]] && echo mv "$line" "path/${line:2:3}.jpg/"; done. That said, obviously if the directory doesn't exist it won't move the file. The reason for the suggestion is any time I use a wildcard, as in, e.g., '*png' in the find command, I like to make subsequent code that will act upon the results of a wildcard find conditional. Apr 1, 2017 at 16:31
  • I mention this because as an example, if one accidentally (or intensional) left the trailing slash off of "path/${line:2:3}.jpg/" so as to be "path/${line:2:3}.jpg", it would rename a file by moving it to ${line:2:3}.jpg as a file not into a directory because the directory didn't exist. Apr 1, 2017 at 16:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .