Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the output of 'system' command in awk

Tags:

awk

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

like image 587
ningyuwhut Avatar asked Sep 15 '25 02:09

ningyuwhut


2 Answers

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
like image 154
Juan Diego Godoy Robles Avatar answered Sep 17 '25 18:09

Juan Diego Godoy Robles


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
like image 41
nu11p01n73R Avatar answered Sep 17 '25 19:09

nu11p01n73R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!