#!/usr/bin/env perl
#===============================================================================
#
# FILE: history_cleaner.pl
#
# USAGE: ./history_cleaner.pl
#
# DESCRIPTION: Cleans th ~/.history file from some entries
#
# REQUIREMENTS: ~/.history
# NOTES: clean the history file and load the new history from file
# cannot be done within this script. It has to be done manually,
# after running the script.
# AUTHOR: Getopt
# VERSION: 1.1
# LAST CHANGE: 30.08.2015
#
#===============================================================================
use v5.18;
use File::Copy;
my $historyfile = "$ENV{HOME}/.history";
my $historydebugfile = "$ENV{HOME}/history_debug";
my $debug = 0;
if ( $debug ) {
if ( !-e $historydebugfile ) { # Test if file does not exist
copy($historyfile, $historydebugfile) or die "Copy failed: $!";
say "DEBUG: $historyfile has been copied to $historydebugfile";
}
else {
say "DEBUG: Working on $historydebugfile";
}
$historyfile = $historydebugfile;
}
sub usage {
say "Usage: history_cleaner delete expr deletes matching expression";
say " history_cleaner auto cleans not useful entries";
say " history_cleaner repair cleans corrupted lines";
}
if ( @ARGV == () || @ARGV[0] !~ m/auto|rep|repair|del|delete/ ) {
usage();
exit;
}
# read the file in an array
open FILE, "<", $historyfile or die "Error opening $historyfile: $!\n";
my @line = <FILE>;
close (FILE);
chomp(@line);
my $minlen = 6; # Minimum length of command line
my @newline;
foreach my $i ( 0 .. $#line ) {
if ( $line[$i] =~ s/^#\+//) {
# $_ is now epoch (we might use it someday)
# $line[$i+1] has the command line
# Delete corrupted lines
if ( $ARGV[0] =~ m/rep|repair/ && $line[$i+1] =~ m/#\+/) {
say "deleted: $line[$i+1]";
next;
}
# Delete small lines
elsif ( $ARGV[0] =~ m/auto/ && length($line[$i+1]) <= $minlen) {
say "deleted: $line[$i+1]";
next;
}
# Delete unneccesary or unwanted commands
elsif ( $ARGV[0] =~ m/auto/ &&
$line[$i+1] =~ m/^(pkg i|pkg d|dmesg|drill|which|chown|chmod|touch|tail|head|host|kill|diff|opie|echo|eval|find|wipe|set|setenv|cat|cal|man|cd|cp|dc|ls|ll|mv|rm|[0-9]|\~|\+|\.|\/|\$)/ ) {
say "deleted: $line[$i+1]";
next;
}
# Delete matched command lines
elsif ( $ARGV[0] =~ m/del|delete/ && $line[$i+1] =~ m/$ARGV[1]/ ) {
say "deleted: $line[$i+1]";
next;
}
else {
push @newline, "#+$line[$i]";
push @newline, $line[$i+1];
}
}
}
system("mv $historyfile $historyfile~");
open FILE, ">", $historyfile or die "Error opening $historyfile: $!\n";
map {
say FILE $_;
} @newline;
close (FILE);
say "To make the changes permanent, you need to run manually:";
say "> history -c && history -L $historyfile\n";