How to derive current date and time and append at the end of each line that contains 'Hello'

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

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.


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.

Tags:

Date

Grep

Awk