ifne: If no command is specified, print usage information.
[moreutils.git] / ts
blobd8d8719f952623dfcba8dfcb424b561d222935f6
1 #!/usr/bin/perl
3 =head1 NAME
5 ts - timestamp input
7 =head1 SYNOPSIS
9 ts [-r] [format]
11 =head1 DESCRIPTION
13 ts adds a timestamp to the beginning of each line of input.
15 The optional format parameter controls how the timestamp is formatted,
16 as used by L<strftime(3)>. The default format is "%b %d %H:%M:%S".
18 If the -r switch is passed, it instead converts existing timestamps in
19 the input to relative times, such as "15m5s ago". Many common timestamp
20 formats are supported. Note that the Time::Duration and Date::Parse perl
21 modules are required for this mode to work.
23 If both -r and a format is passed, the format existing timestamps are
24 converted to the specified format.
26 =head1 ENVIRONMENT
28 The standard TZ environment variable controls what time zone dates
29 are assumed to be in, if a timezone is not specified as part of the date.
31 =head1 AUTHOR
33 Copyright 2006 by Joey Hess <joey@kitenet.net>
35 Licensed under the GNU GPL.
37 =cut
39 use warnings;
40 use strict;
41 use POSIX q{strftime};
43 $|=1;
45 my $rel=0;
46 use Getopt::Long;
47 GetOptions("r" => \$rel) || die "usage: ts [-r] [format]\n";
49 if ($rel) {
50 eval q{
51 use Date::Parse;
52 use Time::Duration;
54 die $@ if $@;
57 my $use_format=@ARGV;
58 my $format="%b %d %H:%M:%S";
59 $format=shift if @ARGV;
61 while (<>) {
62 if (! $rel) {
63 print strftime($format, localtime)." ".$_;
65 else {
66 s{\b(
67 \d\d[-\s\/]\w\w\w # 21 dec 17:05
68 (?:\/\d\d+)? # 21 dec/93 17:05
69 [\s:]\d\d:\d\d # (time part of above)
70 (?::\d\d)? # (optional seconds)
71 (?:\s+[+-]\d\d\d\d)? # (optional timezone)
73 \w{3}\s+\d\d\s+\d\d:\d\d:\d\d # syslog form
75 \d\d\d[-:]\d\d[-:]\d\dT\d\d:\d\d:\d\d.\d+ # ISO-8601
77 (?:\w\w\w,?\s+)? # (optional Day)
78 \d+\s+\w\w\w\s+\d\d+\s+\d\d:\d\d:\d\d
79 # 16 Jun 94 07:29:35
80 (?:\s+\w\w\w|\s[+-]\d\d\d\d)?
81 # (optional timezone)
83 \w\w\w\s+\w\w\w\s+\d\d\s+\d\d:\d\d
84 # lastlog format
85 )\b
87 $use_format
88 ? strftime($format, localtime(str2time($1)))
89 : concise(ago(time - str2time($1), 2))
90 }exg;
92 print $_;