Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: how to delete last symbol

Tags:

bash

shell

awk

I'm trying to extract some information from bash command output:

uptime | awk '{print $3}'

When running it I get this result: 8:27,

How can I delete the last symbol (i.e. the comma)?

like image 588
Mark Egel Avatar asked Nov 28 '22 16:11

Mark Egel


1 Answers

Another variant (replacing awk and sed with cut):

# "unnecessary" echo with evil backticks to get rid of extra spaces
echo `uptime|cut -d, -f1'

appears to work... until the uptime reaches one day (thanks to @sudo_O for pointing out). Then the output format will include the number of days, and we'll need

echo `uptime|cut -d, -f2`

(the latter was my original answer because I tested with uptime > 24h).

UPD: both solutions don't really work: the latter prints uptime hours with no days, the former fails to extract hours because there's no comma separator before them when there is no days -- but the rest of the answer is actually proved by those failures.

The whole approach is error-prone. What happens after months and years? (I seem to recall it still shows N days, but I can err). What if uptime is ever localised? (Did they refuse to do it for the sake of existing scripts?) What does it show for 1 user, "1 user" or "1 users"? If we know all the answers, do we want to depend on them?

If our purpose is showing uptime to the user, extracting the part between 'up' and 'users' with a regular expression would do the trick:

uptime | sed 's/^.*up\(.*\), *[0-9]\+ *users.*$/\1/'

If we want to compare time or collect statistics, something like Linux-specific /proc/uptime will work better (the first column in /proc/uptime is raw uptime seconds).

like image 144
Anton Kovalenko Avatar answered Dec 04 '22 05:12

Anton Kovalenko