Help with awk command

So i understand what it is outputting . but I dont know what any of it means… except the print time $0 part.

command | awk '{ "date" | getline c_time ; close("date") ; getline ; print c_time , $0 ; }'

Can something explain the date piped to getline and close and getline stuff?

I still dont understand it… but I made it run faster by taking out that last getline command.

I’m an awk novice, but it looks like this is meant to tag the logging of a long running command with a date. Quite useful for event driven sources which don’t do dates.

For example:

$ dmesg -w | awk '{ "date" | getline c_time ; close("date") ; getline ; print c_time , $0 ; }'
...
Sun Apr 22 23:50:21 PDT 2018 [965376.638108] usb 1-6.2: new high-speed USB device number 5 using xhci_hcd
Sun Apr 22 23:50:21 PDT 2018 [965376.733291] usb 1-6.2: New USB device found, idVendor=058f, idProduct=6335
Sun Apr 22 23:50:21 PDT 2018 [965376.742026] usb-storage 1-6.2:1.0: USB Mass Storage device detected
Sun Apr 22 23:50:21 PDT 2018 [965376.742167] usbcore: registered new interface driver usb-storage
Sun Apr 22 23:50:21 PDT 2018 [965377.764663] scsi 8:0:0:0: Direct-Access     SD/MMC   Card  Reader     1.00 PQ: 0 ANSI: 0
Sun Apr 22 23:50:21 PDT 2018 [965378.041414] sd 8:0:0:0: [sdd] 62333952 512-byte logical blocks: (31.9 GB/29.7 GiB)
Sun Apr 22 23:50:21 PDT 2018 [965378.042885] sd 8:0:0:0: [sdd] Mode Sense: 03 00 00 00
Sun Apr 22 23:50:21 PDT 2018 [965378.044367] sd 8:0:0:0: [sdd] Assuming drive cache: write through
Sun Apr 22 23:50:21 PDT 2018 [965378.084066] sd 8:0:0:0: [sdd] Attached SCSI removable disk

The getline c_time reads a line from the date command. The next getline reads a line from dmesg command, then the print c_type, $0 is outputing these two together. This will run forever as long as dmesg keeps running, and the -w arg tells it to watch the kernel log and output lines as the kernel emits them.

3 Likes

Not much of awk is used here, this could be shell loop too:
while read line ; do echo "$(date) $line"; done

What awk could buy you is not having to “shell out” on each line because it contains things like strftime built in.

{print strftime(), $0}

The problem with the awk command was it was skipping output… somehow removing the second getline fixed it.