user53029 user53029 - 7 months ago 17
Perl Question

Perl one liner to convert epoch to human readable then remove epoch

First, some background:

We are using code in our .bash_profile that appends a timestamp to the history command.

export HISTTIMEFORMAT="%d/%m/%Y %T "


Then we also have code that appends our command history to a specific location in /root/history/

export HISTFILE=/root/history/.bash_hist-$(who -m | awk '{print $1}')


The "export HISTTIMEFORMAT" command will append the epoch timestamp to the file in /root/history/.

Now the magic happens when we use a perl one-liner to convert the epoch to human readable. (this, btw, is also in .bash_profile)

format_history () {
perl -i -e '$/=undef;my $string=<>;$string=~s/#([0-9] {10}.*\n.*$)/"# ".localtime($1)."#\n#$1"/ge;print $string;' /root/history/.bash_hist-$(who -m | awk '{print $1}')
}

shopt -s histappend
PROMPT_COMMAND="history -a;format_history;$PROMPT_COMMAND"


The end result is a file that contains lines like this for each command:

# Wed Apr 27 10:11:26 2016
#1461769886
vi /root/.bash_profile


I am looking for a way to have perl remove the epoch timestamp once its done converting it but have been unsuccessful so far. I have tried using sed at the end of the line and another perl command. Like this:

First try:

perl -i -e '$/=undef;my $string=<>;$string=~s/#([0-9]{10}.*\n.*$)/"# ".localtime($1)."#\n#$1"/ge;print $string;' /root/history/.bash_hist-$(who -m | awk '{print $1}' | sed '/^#1/ d'


Second try:

perl -i -e '$/=undef;my $string=<>;$string=~s/#([0-9]{10}.*\n.*$)/"# ".localtime($1)."#\n#$1"/ge;print $string;' /root/history/.bash_hist-$(who -m | awk '{print $1}' | perl -i -nle 'print if !/^#1\b' /root/history/.bash_hist-$(who -m | awk '{print $1}'


But as I mentioned these do not work. Can anyone help me find a solution?

Answer

If you don't want the epoch line, why are you writing it?

format_history () {
    local file=/root/history/.bash_hist-$LOGNAME
    perl -i -pe 's/^#(\d{10})$/"# ".localtime($1)/e' "$file"
}