How to move an old file to another folder

In my folder, I have a file whose suffix is ​​the date that this file was created, for example: file.log2012-08-21, file.log2012-08-20 ... Now, how can I move a file that is older, than 2012-08-20? I know how I can do this day after day: mv file.log2012-08-19 /old/ , but I don’t know when to stop ... does the mv command have a parameter to make this easier?

+4
source share
4 answers

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

This will move all files older than "2012-08-20" to the / old folder. Similarly, you can change "2012-08-20" to indicate the specific date you want. Note that the file suffix is ​​assumed to be a date stamp, but the prefix can be any name.

If you just need to move files older than a certain day, I think rkyser answer is better for this.

-1
source

You can use find with the -mtime option. This assumes that the file suffix, as described above, corresponds to the print date in the file.

  • -mtime +1 means finding files for more than 1 day.
  • -mtime -1 means finding files for less than 1 day.
  • -mtime 1 means search files 1 day

Example (updated):

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

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

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

Assuming your log files are not changed after their last line:

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

Note: the .log2012-08-20 file will be moved with this command. If you do not want this, use the previous file:

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

You may need to write a small script for this. If all your files are in a specific naming convention, for example file.log2012-08-21 , then something like this will 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 actually do this, it is recommended that you change the mv command to echo to check if the files are moved correctly.

0
source

All Articles