lundi 13 septembre 2010

Nettoyer automatiquement la liste de fichiers/documents récents

Il peut être intéressant de nettoyer les fichiers récents de certaines entrées sans pour autant supprimer toutes les entrées.

J'ai donc un exemple de script qui pourra vous aider dans ce sens.

Pour l'utiliser, créez un fichier (par exemple "monScript") et copiez-y le code suivant:

#!/usr/bin/perl
use strict;

###
# To configure everything
  # File to clean (actually only xml-built with boommark as keyword at the moment)
my $file = "/home/login/.recently-used.xbel"; #replace by your login
my $filter_keyword_bgn = "<bookmark ";
my $filter_keyword_end = "<\/bookmark>";

  # List of regexp to look for
my @searched_list = (
          "searched_keyword_1"
#        , "searched_keyword_1" # keyword2, etc...
             );

  # Actions: 1=leave only if keyword found ; 0=remove if keyword found
my $const_action  = 0;

###
# Must not be modified
my $copy = 1; # Initialize to 1 to copy the begining of the file

my $tmp_file = $file.".tmp";
my $tmp_regexp;

#Processing
if (-f $file ){
  #Filtered copy to a temporary file
    open (FILE_SRC , "<".$file);

    unlink $tmp_file if (-f $tmp_file);
    open (FILE_DST , ">".$tmp_file) or die();

    while (<FILE_SRC>){
        if ($_ =~ m/$filter_keyword_bgn/i) {
            $copy = !$const_action;

          #Loop on filter_keyword
            foreach $tmp_regexp (@searched_list) {
                if ($_ =~ m/.*$tmp_regexp.*/i) {
                    $copy = $const_action;
                    last;
                }
            }
        }
        print FILE_DST $_ if (1 == $copy);
        $copy = 1 if $_ =~ m/$filter_keyword_end/i;
    }

    close (FILE_DST);
    close (FILE_SRC);

  #Final copy from the filtered result to the original file
    #Erase the previous file
    unlink $file;

    #Open the files in read or write
    open(FILE_SRC, "<".$tmp_file);
    open(FILE_DST, ">".$file);

    #Copy the result to the original file
    while (my $len = sysread(FILE_SRC, my $buffer, 512))
    {
      syswrite(FILE_DST, $buffer, $len);
    }
    close(FILE_DST);
    close(FILE_SRC);

    #Remove the temporary file
    unlink $tmp_file;
}

Comme c'est du perl vous aurez besoin de ce paquet : perl

Rendez votre fichier exécutable et copiez-le dans un dossier bin inclus dans votre path (echo $PATH dans un terminal).

Pour le configurer: cherchez la liste @searched_list et mettez tous les mots clefs qui vous intéresse (rechercher des infos sur les tables dans perl si vous ne savez pas comment faire).

Vous pouvez choisir d'effacer ou ne laisser uniquement les entrées que vous mettez dans @searched_list grâce à la variable $const_action.

Il ne reste plus qu'à exécuter le script régulièrement en l'ajoutant à cron.

Aucun commentaire:

Enregistrer un commentaire