3

I try to extract the hostname from the following string (created using who am i):

username pts/0        2010-10-05 17:30 (www.example.com)

I need a solution which also works if (www.example.com) is not present which is the case when I am logged in locally. Furthermore the solution also has to work on a Mac where who am i returns the following string:

username ttys006      Oct  5 16:47 (www.example.com)

The problem is that the mac puts spaces in the date which makes it hard to use cut. I think, there must be a solution using sed to extract the substring, but I have problems figuring out how to use sed appropriately.

Update: Mad's approach

This approach only works well if there are actually parentheses present. If not, the following happens:

$ who am i | cut -f2 -d '(' | tr -d ')'
username ttys006      Oct  5 16:47
t6d
  • 547

4 Answers4

15

This is where awk is the best tool. awk -F"[()]" '{print $2}' should pull out what's in parenthesis. Prints nothing if it's not there. So...

$ who am i | awk -F"[()]" '{print $2}'
www.example.com


--Christopher Karel

5

You can use who am i | grep -o -e "\((.*)\)" on both systems, and it simply returns an empty string if you're logged in locally.

2

If you like cut (and I'm not saying there aren't more elegant ways to do it, but you chose the tool, and I rather like cut, too), try

who am i | cut -f2 -d\( | tr -d ')'

You take the second field, using left-paren as the separator (whcih will include the closing paren, though not the opening one), and then use tr to delete the close-paren.

I'm not sure about the case when the string isn't present, as all the times I try it on a locally logged-on machine I get something returned in the brackets. Could you give an example of what you get under those circumstances?

MadHatter
  • 81,580
2

Here's a sed version which works with or without parentheses around the hostname or spaces in the date:

who am i | sed 's/.* (\?\([^)]*\))\?$/\1/'