tags:

views:

160

answers:

3

I'd like to trim the output from uptime

20:10  up 23 days,  3:28, 3 users, load averages: 3.84 1.06 0.64

so that it just shows:

23 days

I've tried using sed, but I'm not sure it's the right tool for the job, and don't have much experience using it.

How can I achieve the output I want?

+1  A: 

Consider using cut.

  uptime | tr "," " " | cut -f6-8 -d" "

seems to work on my MacBook. Here I've also used tr to kill an extraneous ",". There is a bit of an issue with different formats for short and long uptimes.


A possible sed solution:

uptime | sed 's/.*up \([^,]*\), .*/\1/'

which doesn't rely on the string "days" appearing in the output of uptime.

dmckee
Would the downvoter care to explain? Doesn't work on your system? Don't like some detail of one of these solutions?
dmckee
Strange down vote... Works fine, so +1.
Bart Kiers
Wasn't me who downvoted... both seem logical - maybe they were just in a bad mood!
Rich Bradshaw
Drive by downvotes happen. I just like to know if my solution is broken.
dmckee
Didn't work for me on Arch Linux. Sorry I forgot to comment after down-voting.
icco
@icco: With more info I might be able to fix it, but the gory details of the output from the "standard" utilities can vary from unix to unix, so this kinds of pipelines sometimes need tweaking...
dmckee
+4  A: 
uptime | sed -E 's/^.+([0-9]+ days).+$/\1/'
jtbandes
Awesome - that \1 was what I couldn't work out!
Rich Bradshaw
\1 means the first captured group (which is in parentheses).
jtbandes
Note that when the substring `days` is not present (when a reboot has happened less than a day ago), this solution won't work.
Bart Kiers
Good point! The other answer seems a little better now…
Rich Bradshaw
+3  A: 

you can just use the shell without any external tools

$ var="20:10  up 23 days,  3:28, 3 users, load averages: 3.84 1.06 0.64"
$ var=${var/#*up}
$ echo ${var%%,*}
23 days
ghostdog74
That's clever - didn't know you could do that!
Rich Bradshaw
Nice. I knew, in theory, but I never remember to use the bash extensions. (and it might be worth noting that this won't work with all shells...)
dmckee
@dmckee, what are the shells it won't work on?
ghostdog74
The original bourne shell, csh, don't know about ksh...all of unix doesn't run bash.
dmckee