3

I have a file of the following structure:

#1552342335
ls
#1552342359
date
#1552342380
cat .bash_history 

i.e. timestamp followed by a text line. I want to process every timestamp line using shell's date (something like date -d ${1/\#/@} '+%F %T'), merge it with the next line and wrap with table tags, i.e. the output would be the following:

<tr> <td>2019-03-11 18:12:15</td> <td><pre>ls</pre></td> </tr>
<tr> <td>2019-03-11 18:12:39</td> <td><pre>date</pre></td> </tr>
<tr> <td>2019-03-11 18:13:00</td> <td><pre>cat .bash_history</pre></td> </tr>

I understand it would be something like awk 'NR % 2 {print | " <something here>" } !(NR % 2) {p=$0}' input_file - but I can't find the way to implement all the necessary transformations in one command.

  • GNU awk, available on most systems with bash, can do this timestamp conversion internally without running the date program, and is probably 10 to 100 times faster. – dave_thompson_085 Mar 13 at 9:27
2

Beware the following code lacks error-handling. Explanations are embedded by way of inline comments

awk '{

    #strip leading "#", run through date and read into $0
    gsub(/^#/, ""); "date -d @"$0" \"+%F %T\"" | getline; 
    #wrap with table tags and print
    printf "<tr> <td>%s</td>", $0;
    #read the subsequent "non-date" line
    getline;
    #wrap with table tags and print
    printf " <td><pre>%s</pre></td> </tr>\n", $0

}' file
  • thank you so much!!! (it took me a while to understand how your magic code works...) – Vasily A Mar 13 at 5:49
4

With GNU Awk (gawk) you could use the built-in strftime:

gawk '
    NR%2 {ts = strftime("%F %T",substr($0,2)); next} 
         {printf("<tr> <td>%s</td> <td><pre>%s</pre></td> </tr>\n",ts,$0)}
' input_file 
<tr> <td>2019-03-11 18:12:15</td> <td><pre>ls</pre></td> </tr>
<tr> <td>2019-03-11 18:12:39</td> <td><pre>date</pre></td> </tr>
<tr> <td>2019-03-11 18:13:00</td> <td><pre>cat .bash_history </pre></td> </tr>
  • cool, that's even better! thank you! – Vasily A Mar 13 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.