3

These are the files in the directory:

Ford-Mustang-001.jpg
Ford-Mustang-002.jpg
Ford-Mustang-003.jpg

Chevy-Impala-001.jpg
Chevy-Impala-002.jpg
Chevy-Impala-003.jpg

I would like to sort these into subfolders:

/Mustang
/Impala
4

using prename (perl renamer)

prename 'if(/(.+?)-(.+?)-(.*)/){mkdir $2; $_="$2/$_"}' *.jpg
  • This works perfect. Thanks! Now would using the first part of the filename be as simple as changing the "2" to "1"? – Mike Nov 5 '16 at 18:17
  • yes: each parenthesis grout captures a matching string available under $1, $2... – JJoao Nov 5 '16 at 19:23
  • 1
    does this call mkdir for each file ? if so, shouldn't it use -p flag ? – Ciprian Tomoiagă Nov 6 '16 at 0:18
  • 1
    @CiprianTomoiaga, this is the perl function mkdir not the bash mkdir. Internally the function returns false is dir already exists. In this case there is no problem in ignoring it. – JJoao Nov 6 '16 at 1:11
  • 2
    One liners are all right, but consider adding at least some explanation. – heemayl Nov 6 '16 at 4:51
6

The obvious answer:

Just make the directories and put the files in them.

mkdir Mustang Impala
mv *Mustang*.jpg Mustang/
mv *Impala*.jpg Impala/

This is called file globbing; it's a shell feature.


If you have huge numbers of files and need to make many different directories to accommodate them, try JJoao's answer.

  • Wildcard, OP wants to move files into a sub-folder based on filename part so it's kinda obvious that the above is just an example. I know you can do better than this... – don_crissti Nov 5 '16 at 17:23
  • @don_crissti, I would think this is just an example, if I hadn't been looking at questions from new users all morning. ;) I upvoted the other answer, but I'll leave this here in case someone is looking for the stupid-simple solution. – Wildcard Nov 5 '16 at 17:26
  • 1
    As someone in the process of learning the commands, this is helpful as well. Thanks! – Mike Nov 5 '16 at 18:18
0

I would split thw filename using awk awk {split $0, a, "-"; mkdir a[1]; mv $0 a[1]/} if you want to rename you could do this with the mv program

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.