Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have to make a bash script that do a gzip of a file if is older than 60 days, and move it in a subdir which name is the beginning of the filename. Here an example of the files I have to work with:

-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux21-x1.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 GLUX21-x34.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux226.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux228.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux230.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux232.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux234.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux236.csv
-rw-r--r-- 1 X X    0 2012-10-15 11:19 glux255.csv

So, for example, the glux21-x1.csv should be gzipped and moved in the glux21 subdir, as for the GLUX21-x34.csv file. The glux255.csv should go in the glux255 subdir.

share|improve this question
My advice, get some code together, test it. If you have any troubles someone will help you. But don't expect us to do your homework ;) – Torian Oct 15 '12 at 10:10
Do you know logrotate? It could do a lot of what you're after and is flexible (eg. with the lastaction directive). – sr_ Oct 15 '12 at 10:23
up vote 4 down vote accepted
find . -ctime -60 -maxdepth 1 -type f | while IFS= read x
    gzip -9 "$x"  # compress it
    D=${D/-*/}    # remove suffix and everything after the -

    mkdir -p "$D" # create dest sub folder
    mv $x.gz "$D"   # move it

This will process all files you needed, and put them into different sub folder respectly.

share|improve this answer
I don't think that the above will handle the situation where special characters (such as spaces) are present in the filename. – mdpc Oct 16 '12 at 20:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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