Create the shortest script that organizes all the logs by month and date.



organize <folder to scan> <folder to place logs> 
  • folder cannot be root
  • the two folder should be different and not contain one another


The script should scan all the *.log files in <folder to scan> and copy them to <folder to place logs> in sub-folders corresponding to the year and month of the last modified time of the log file, named like year_month.


organize /var/log/apache2 /temp/logs  

would give folder structure like this:

|-- 2014_01
|-- 2014_02
|-- 2014_03
|-- 2014_04
|-- 2014_05

Languages, environment

All languages and OSs are permitted but need to be specified.

But since this is a question, script languages (python, bash, windows batch) will be more fit from the start.

  • \$\begingroup\$ Are we sorting them based on create date, modified date, filename, etc? If name, how is the name formatted? \$\endgroup\$
    – Geobits
    Aug 5, 2014 at 20:07
  • \$\begingroup\$ @Geobits A edited to make it more clear, "sub-folders corresponding to the year and month of the last modified time of the log file" \$\endgroup\$ Aug 5, 2014 at 20:12
  • 2
    \$\begingroup\$ Is target folder exists or it should be created first? \$\endgroup\$
    – Kondybas
    Aug 6, 2014 at 1:23

5 Answers 5


Bash - 79 bytes

stat -c" $2/-%n-%y" $1/*.log|awk -F- '{d=$1$3"_"$4;system("mkdir"d";cp "$2d)}'

Batch - 104 bytes

@cmd/von/c"for /r %1 %%a in (*.log)do @set a=%%~ta&set a=!a:~6,4!_!a:~3,2!&mkdir %2\!a!&copy %%a %2\!a!"
  • \$\begingroup\$ What if there are more than one log file per month? \$\endgroup\$
    – Kondybas
    Aug 6, 2014 at 6:57
  • \$\begingroup\$ @Kondybas that would be fine. \$\endgroup\$
    – unclemeat
    Aug 6, 2014 at 6:58
  • \$\begingroup\$ @Kondybas Do you mean more than one log file with the same name per month? \$\endgroup\$
    – unclemeat
    Aug 6, 2014 at 7:00
  • \$\begingroup\$ Eeeh, oops! You're right :) \$\endgroup\$
    – Kondybas
    Aug 6, 2014 at 7:02

Powershell (124 bytes)

Get-ChildItem $($s+"\*.log")|%{$n=$d+"\"+$_.LastWriteTime.ToString("yyyy_MM");if(!(Test-Path $n)){md $n}mi $($s+$_.Name) $n}

Has the added bonus of scanning for only .log files in the given folder if there are multiple file types. If not, then I can knock this down to 112. $s is the full source folder path, and $d is the destination folder path.


Cobra - 223

OS: Any with Mono/.NET

Because this is the perfect task for an obscure compiled language! < /sarcasm>

class P
    def main
        for f in Directory.getFiles(a,'*.log')

Bourne Shell / FreeBSD 9.2+ - 92(83) bytes

ls -lD"%Y_%m" $1/*.log|cut -wf6-|while read A B;do mkdir $2/$A;cp $1/$B $2/$A;done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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