如何在Bash(正常运行时间)中处理特定的输出?

时间:2019-06-12 13:52:41

标签: linux bash uptime

所以不久前我一直在试验Bash,我想操纵“运行时间”命令的输出。例如,如果正常运行时间为5分钟,我设法将x分钟的输出更改为0:05,但是其余的一切消失了。

在不影响当前正常运行时间输出的情况下,我还应该使用哪种方法显示时间,用户数量及其平均负载。

这是所需的输出:21:08:13向上0:10,3个用户,平均负载:0.30,0.30,0.25

任何帮助将不胜感激!

since="`uptime --since`"
start="`date --date "$since" '+%s'`"
now="`date '+%s'`"
sec=$((now-start))

days=$((sec/(60*60*24)))
sec=$((sec-days*(60*60*24)))

hr=$((sec/(60*60)))
sec=$((sec-hr*(60*60)))

min=$((sec/60))
sec=$((sec-min*60))

rest="$(uptime | perl -npe'{s/(.*,\s+)(\d+\s+user)/$2/}')"

printf "%d(days), %02d:%02d:%02d(hms), %s\n" $days $hr $min $sec "$rest"

当前输出

0(days), 00:34:00(hms), 3 users, load average: 0.09, 0.14, 0.14

2 个答案:

答案 0 :(得分:1)

这可能是一种只使用正常运行时间,日期以及当然使用bash的方式:

#!/bin/bash

since="`uptime --since`"
start="`date --date "$since" '+%s'`"
now="`date '+%s'`"
sec=$((now-start))

days=$((sec/(60*60*24)))
sec=$((sec-days*(60*60*24)))

hr=$((sec/(60*60)))
sec=$((sec-hr*(60*60)))

min=$((sec/60))
sec=$((sec-min*60))

printf "%d(days), %02d:%02d:%02d(hms)\n" $days $hr $min $sec

答案 1 :(得分:1)

使用您的输出到名为date的文件中,我尝试了此操作:

  # Calculate the upper bound for the random number generator
  # upper_bound = 1,000,000
  upper_bound = 10**6

  # n will be an integer with a minimum possible value of 0,
  # and a maximum possible value of 999,999
  n = SecureRandom.random_number(upper_bound)

  # Convert the integer n to a string
  # unpadded_str will be "0" if n == 0
  # unpadded_str will be "999999" if n == 999999
  unpadded_str = n.to_s

  # Pad the string with leading zeroes if it is less than
  # 6 digits long.
  # "0" would be padded to "000000"
  # "123" would be padded to "000123"
  # "999999" would not be padded, and remains unchanged as "999999"
  padded_str = unpadded_str.rjust(6, '0')
相关问题