0

So what I've been trying to do is replace a certain output in bash with awk. But I can't seem to get it to work. I'm trying to replace the $6 output from "uptime" to 'user' instead of 'users'. How can this be done with awk or sed?

This is a "part" of my current script.

#!/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))

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

printf `uptime | awk '{print $1}'`" up %2d:%02d,  %s\n" $hr $min "$rest"

The output is as following 21:08:13 up 0:10, 3 users load average: 0.30, 0.30, 0.25

2
  • 1
    Why not just uptime | awk '{ sub("users,","user,") }1'
    – Inian
    Jun 13, 2019 at 8:50
  • I don't understand what you want. Is it just the final line of your script that you are talking about? If so, please remove all the irrelevant commands, and write a minimal example. Then, could you please show the output of uptime as you see it, and what you would like it to show?
    – Sparhawk
    Jun 13, 2019 at 9:25

2 Answers 2

1

This looks like a lot of effort for something very trivial. Here is a simple sed command that replaces 'users' with 'user' in uptime output:

$ uptime | sed 's/users/user/'
 12:28:39 up 17:16,  7 user,  load average: 1.67, 1.41, 1.31
0

sed command

uptime| sed '/users/s/users/user/g'

19:10:14 up 1 min, 2 user, load average: 0.42, 0.19, 0.07

awk

uptime| awk '/users/{gsub("users","user",$0);print $0}'
 19:11:19 up 2 min,  2 user,  load average: 0.14, 0.15, 0.06

python

!/usr/bin/python
import subprocess
cmd="uptime"
import re

k=subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True).communicate()[0].strip().split('\n')
#print k
for i in k:
    l=re.sub("users","user",i)
    print l

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .