-2

I am trying to achieve this using bash

I have a directory of files, a sample to get the picture is below:

January 2010 MA - C3 Edexcel.pdf
January 2010 MS - C3 Edexcel.pdf    
January 2010 QP - C3 Edexcel.pdf    
January 2011 MA - C3 Edexcel.pdf 
January 2011 MS - C3 Edexcel.pdf    
January 2011 QP - C3 Edexcel.pdf

I am looking for a command that will take the three files from each year and put it into a folder for that year, for example, the first three files should go into a folder called 2010 and the second group of three files should go into a folder called 2011.

So what I am trying to do is

 mkdir 2010| mv *2010* 2010

For every year in the file

To be clear, the folder is much larger than what I showed, meaning doing it year by year would take too much time

Is this possible?

2

This snipet of an script will do what you ask for several years:

for i in $(seq 2010 2020); do 
    mkdir -p "$i" && 
    mv *"$i"*.pdf "$i"
done
  • You should really put $i into quotes ("$i"). Once you do that, you can discard the curly braces, so mv *"$i"*.pdf "$i". And you don’t need the curly braces in mkdir "$i", either. You don’t need the ; at the end of the line, and I do things like this just fine without putting the / at the end of the directory name.  And consider using mkdir -p, so the command doesn’t fail if the directory already exists. – G-Man Jan 27 '18 at 23:01
0

an easy way to understand it

mkdir 2010 && mv *2010*pdf !$

& same thing for 2011 ...

here a solution to loop on many years files

for i in $(seq 0 9) ; do mkdir 201${i} && mv *201${i}*pdf !$ ; done 
  • The directory is much larger than what I showed, meaning it would take too long to do this – SamRob85 Jan 27 '18 at 19:55
  • whatever the method you will use it will take time :) but if you have too many 'years' to manage, you can script it in a loop (I edit answer to show how to) – francois P Jan 27 '18 at 19:57
  • 1
    Please use $(…) instead of backticks. – Isaac Jan 27 '18 at 21:54
  • 1
    What are you expecting the !$ to match? – roaima Jan 27 '18 at 22:29
  • !$ matches the last command parameter (only parameter) so directory name here – francois P Jan 28 '18 at 17:20

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.