Add Timestamps Using the Ts Command In Linux

It can be useful to add current timestamp to each of the lines in files through the Linux command-line. ts (timestamp input) is a handy utility and a part of moreutils package in Linux which does just that. With ts, you can pipe the input file and directly add timestamps to each of the lines. This example uses Linux Mint to show how to use ts.

Installing ts:

First, install ts as it is not installed by default. Open the Linux shell and type in:

 sudo apt install moreutils

installing moreutils

Using ts:

After ts is installed, try running it. As a standalone command, it will simply display the current timestamp on a new line every time on hitting Enter. To force exit, press Ctrl-C.

running ts as a standalone command

To pipe the output of any file as an input to ts, open the file using cat command and include ts. So, suppose, to show a timestamp on each of the lines of a text file named timestamp_lines.txt, the command will be:

 cat timestamp_lines.txt|ts

piping text file output to ts

This will add the complete timestamp on each of the lines in that file.

ts is most useful when parsing through logs. Simply open the log files with ts, and as soon as new entries are found, the current timestamp will be added to those entries.

So, to see the last 5 lines of the log file named dpkg.log, the complete command will be :

 tail -5 /var/log/dpkg.log|ts

adding timestamps to logs with ts


The leftmost column of the output has the timestamp added to each of the lines. You can also redirect the output to a new file named ts_dpkg_output.txt if needed.

 tail -5 /var/log/dpkg.log|ts > ts_dpkg_output.txt


The default format for ts is sufficient to get details of the date and time. You can also use a relative time format if needed. For this, add the -r parameter to ts. So, the command for that will look something like this:

 tail -5 /var/log/dpkg.log|ts -r

using the relative parameter in ts command

There is also the –s parameter which will show incremental timestamps. What this means is it will show incremental timestamps when running a program. This is useful in tracing the program output.

adding incremental timestamps using ts

There are different ways in which you can customize how the timestamps appear. By default, the format is %b %d %H:%M:%S. To take a look at other options, use the man page for ts:

 man ts

man page for ts

It is a useful Linux command-line tool that you can include in shell scripts that run backups or parse through logs.

All done.

Comments are closed.