How to move old file to another folder

2019-04-09 18:19发布

问题:

in my folder I have file which suffix is date when this file was created for example: file.log2012-08-21, file.log2012-08-20 ... Now how I can move file which is older then 2012-08-20 ? I know how I can do this day by day: mv file.log2012-08-19 /old/ but I dont know when to stop ... is there some parameter in command mv to do this easier ?

回答1:

ls -l | awk '{print $NF}' | awk 'substr($0, length($0)-9, length($0)) < "2012-08-20" {system("mv "$0" /old/")}'

This will move all the files older than "2012-08-20" to the folder "/old". Likewise, you can change the "2012-08-20" to specify particular date you want. Note this assumes that the file suffix is a date stamp, but the prefix can be any name.

If you just need to move files older than a certain days, then I think rkyser's answer is better for that.



回答2:

You could use find with the -mtime parameter. This assumes that the file suffix as mentioned above matches the datestamp on the file.

  • -mtime +1 means find files more than 1 day old
  • -mtime -1 means find files less than 1 day old
  • -mtime 1 means find files 1 day old

Example (updated):

find . -type f -mtime +1 -name "file.log*" -exec mv {} /old/ \;

or if you only want to find in the current directory only add -maxdepth 1 (otherwise, it will search recursively):

find . -maxdepth 1 -type f -mtime +1 -name "file.log*" -exec mv {} /old/ \;


回答3:

Assuming your log files are not modified after their last line is written:

find . ! -newer file.log2012-08-20 | xargs -r -IX mv X /old/

Note: with this command file.log2012-08-20 would be moved as well. If you don't want it, use the previous file:

find . ! -newer file.log2012-08-19 | xargs -r -IX mv X /old/


回答4:

You may need to write a small script for this. If all you files are in a specific naming convention like file.log2012-08-21, then something like this would do the work.

since=$(date --date="2012-08-20" +%s)
for file in `ls -1 --color=none`
do
    date=$(date --date="${file#file.log}" +%s)
    [ $date -lt $since ] && mv -v $file /old/
done

Before you really do this, it is a good idea to change the mv command to echo to see if the files about to be moved is right.



标签: linux shell