简体   繁体   English

如何将当前时间戳连接到bash上的管道输入?

[英]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. 我想使用ts或awk(gawk)命令来连接管道输入上的时间戳。 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) 在这里输出(按'q'退出顶部)

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" 这对我来说是命令“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 . 我用Linux top: procps version 3.2.8GNU grep 2.6.3GNU 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: 我不知道ts做什么,但是用gawk打印每行输入的当前时间你只需要调用strftime(),当你使用awk时你永远不需要grep所以我怀疑你需要GNU awk所需要的是:

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. 您可能需要在管道中的某个地方添加对UNIX工具stdbuf的调用,如果缓冲被证明是一个问题,但如果您之前的管道工作,那么我也期望这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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