Search code examples
linuxbashawkpipemilliseconds

want to add milliseconds in time stamp of console output using gawk bash


I am using following snippet to add timestamp to console output

command | gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }'  

how to add milliseconds to it?


Solution

  • Why not a simple bash solution? You can read each line and prepend a timestamp using the date command, e.g.

    command | while read -r line; do printf "%s %s\n" "$(date +'%F %T.%03N')" "$line"; done
    

    Example Use/Output

    Sample lines:

    $ cat dat/captnjack.txt
    This is a tale
    Of Captain Jack Sparrow
    A Pirate So Brave
    On the Seven Seas.
    

    Timestamped output:

    $ cat dat/captnjack.txt | 
    while read line; do printf "%s %s\n" "$(date +'%F %T.%03N')" "$line"; done
    2022-06-24 00:45:28.030 This is a tale
    2022-06-24 00:45:28.031 Of Captain Jack Sparrow
    2022-06-24 00:45:28.033 A Pirate So Brave
    2022-06-24 00:45:28.035 On the Seven Seas.
    

    (note: thank you @jhnc for the GNU date %03N specifier)

    With bash you can also use process substitution to feed the timestamp loop, e.g.

    while read -r line; do 
      printf "%s %s\n" "$(date +'%F %T.%03N')" "$line"
    done < <(command)