I have the following file party.txt that contains something like the following:
Hello Jacky
Hello Peter
Bye Johnson
Hello Willy
Bye Johnny
Hello Mar
gawk (and recent versions of mawk) have a built-in time/date function, so there is no need to use external tools there.
gawk '/Hello/{print NR " - " $0 " - " strftime("%Y-%m-%d")}' party.txt
This solution should work with any awk:
awk '/Hello/ {cmd="(date +'%H:%M:%S')"; cmd | getline d; print d,$0; close(cmd)}' party.txt
The magic happens in close(cmd) statement. It forces awk to execute cmd each time, so, date would be actual one each time.
cmd | get line d reads output from cmd and saves it to d.
awk 'BEGIN{"date +'%Y-%m-%d'"|getline d;}/Hello/{print $0,d}' file
will give you:
Hello Jacky 2012-09-11
Hello Peter 2012-09-11
Hello Willy 2012-09-11
Hello Mary 2012-09-11
Hello Wendy 2012-09-11
If you're open to using Perl:
perl -MPOSIX -lne 'if (/Hello/){ print "$_ " . strftime "%Y-%m-%d",localtime }' party.txt
produces this output
Hello Jacky 2015-10-01
Hello Peter 2015-10-01
Hello Willy 2015-10-01
Hello Mary 2015-10-01
Hello Wendy 2015-10-01
Here's how it works:
-n loops around every line of the input file, do not automatically print each line
-l removes newlines before processing, and adds them back in afterwards
-e execute the perl code
$_ is the current line
-MPOSIX loads the POSIX module, which includes strftime
localtime and strftime prints the time, given the format %Y-%m-%d
using posix sed (and a sub shell due to missing time function in sed)
sed -n "/^Hello/ s/$/ $( date +'%Y-%m-%d' )/p" party.txt
return
Hello Jacky 2016-11-10
Hello Peter 2016-11-10
Hello Willy 2016-11-10
Hello Mary 2016-11-10
Hello Wendy 2016-11-10
One way using awk:
awk -v date="$(date +"%Y-%m-%d %r")" '/Hello/ { print $0, date}' party.txt
Results:
Hello Jacky 2012-09-11 07:55:51 PM
Hello Peter 2012-09-11 07:55:51 PM
Hello Willy 2012-09-11 07:55:51 PM
Hello Mary 2012-09-11 07:55:51 PM
Hello Wendy 2012-09-11 07:55:51 PM
Note that the date value is only set when awk starts, so it will not change, even if the command takes a long time to run.