简体   繁体   中英

How can I concatenate the current timestamp to a piped input on bash?

I want to use the ts or awk (gawk) command to concatenate timestamps on piped inputs. However, the start time of the program is fixed. I would like to concatenate the timestamp of the moment when input occurs rather than a fixed time.

command here

top | grep compiz |ts '%H:%M:%S' | awk '{print $1, $11}' > cpu_timestamp.txt

output here(push 'q' to quit the top)

16:23:04 37.5
16:23:04 4.0
16:23:04 4.0
16:23:04 3.7
16:23:04 2.3
16:23:04 1.7

but, I want like this

16:23:04 37.5
16:23:05 4.0
16:23:06 4.0
16:23:07 3.7
16:23:08 2.3
16:23:09 1.7

This works for me with command "bash"

top -b | grep --line-buffered "bash" | ts '%H:%M:%S' | awk '{print $1, $11}'

Output:

09:52:58 0.1
09:52:58 0.0
09:52:58 0.1
09:53:01 0.1
09:53:01 0.0
09:53:01 0.1
09:53:04 0.1
09:53:04 0.0
09:53:04 0.1
...

I used Linux with top: procps version 3.2.8 , GNU grep 2.6.3 and GNU Awk 3.1.7 .

I've no idea what ts does but to print the current time for each line of input with gawk you just call strftime() and you never need grep when you're using awk so I suspect all you need with GNU awk is:

top | awk '/compiz/{strftime("%H:%M:%S"), print $1, $11}' > cpu_timestamp.txt

You might need to add a call to the UNIX tool stdbuf somewhere in the pipeline if buffering proves to be an issue but if your previous pipeline worked then I'd expect this one to too.

This could be a lot quicker if you just inquiry about targeted process:

ps -C compiz u
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root      4236  0.0  0.0      0     0 ?        S<   oct01   0:00 compiz

or

ps -C compiz ho pcpu
 0.1

Then:

printf "%(%T)T %6.2f\n" -1 $(ps -C compiz ho pcpu)
10:37:37   0.10

and

while :;do printf "%(%T)T %6.2f\n" -1 $(ps -C compiz ho pcpu) ; sleep 3 ; done
10:38:31   0.10
10:38:34   0.20
10:38:37   0.10
10:38:41   0.10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM