tags:

views:

68

answers:

5

Hi!

I need to get a username from an Unix path with this format: /home/users/myusername/project/number/files

I just want "myusername" I've been trying for almost a hour and I'm completely clueless.

Any idea?

Thanks!

+5  A: 

Maybe just /home/users/([a-zA-Z0-9_\-]*)/.*?

Note that the critical part [a-zA-Z0-9_\-]* has to contain all valid characters for unix usernames. I took from here, that a username should only contain digits, characters, dashes and underscores.

Also note that the extracted username is not the whole matching, but the first group (indicated by (...)).

phimuemue
He says his path is `/home/users/myusername/project/number/files`. Your regexp may only find `users`.
TK
@TK: You're completely right. But I think he'll be clever enough to adapt it to his needs.
phimuemue
You also need to be careful about anchoring. Any user can create the file `/tmp/home/users/root/project/number/files` :-)
psmears
+1  A: 

Check http://rubular.com/r/84zwJmV62G. The first match, not the entire match, is the username.

TK
A: 
(\/home\/users\/)([^\/]+)

The 2nd capture group (index 1) will be myusername

Robusto
+2  A: 

The best answer to this depends on what you are trying to achieve. If you want to know the user who owns that file then you can use the stat command, this unfortunately has slightly different syntax dependant on the operating system however the following two commands work

Max OS/X

stat -f '%Su' /home/users/myusername/project/number/files

Redhat/Fedora/Centos

stat -c '%U' /home/users/myusername/project/number/files

If you really do want the string following /home/users then the either of the Regexes provided above will do that, you could use that in a bash script as follows (Mac OS/X)

USERNAME=$(echo '/home/users/myusername/project/number/files' | \
  sed -E -e 's!^/home/users/([^/]+)/.*$!\1!g')
Steve Weet
+1  A: 
Alan Horn