I have the following file party.txt
that contains something like the following:
Hello Jacky
Hello Peter
Bye Johnson
Hello Willy
Bye Johnny
Hello Mary
Hello Wendy
I used the grep hello
to capture the contents, but when I use the print date +"%Y-%m-%d'
and append to it, I cannot, and I will get many 0
per line.
cat party.txt | grep Hello | awk '{ print date +"%Y-%m-%d"}'
What could I be missing?
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With