I have a file and a field is a time stamp like 20141028 20:49:49
, I want to get the hour 20
, so I use the system
command :
hour=system("date -d\""$5"\" +'%H'")
the time stamp is the fifth field in my file so I used $5
. But when I executed the program I found the command above just output 20
and return 0 so hour is 0 but not 20
, so my question is how to get the hour in the time stamp ?
I know a method which use split
function two times like this:
split($5, vec, " " )
split(vec[2], vec2, ":")
But this method is a little inefficient and ugly.
so are there any other solutions? Thanks
Another way using gawk
:
gawk 'match($5, " ([0-9]+):", r){print r[1]}' input_file
If you want to know how to manage externall process output in awk
:
awk '{cmd="date -d \""$5"\" +%H";cmd|getline hour;print hour;close(cmd)}' input_file
You can use the substr
function to extract the hour without using system
command.
for example:
awk {'print substr("20:49:49",1,2)}'
will produce output as
20
Or more specifically as in question
$ awk {'print substr("20141028 20:49:49",10,2)}'
20
substr(str, pos, len)
extracts a substring from str
at position pos
and lenght len
if the value of $5
is 20141028 20:49:49
,
$ awk {'print substr($5,10,2)}'
20
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