Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
awk '/user/ {print $1 }' /etc/userdomains | sed 's/://'

the format of /etc/userdomains is

domain.tld: user
otherdomain.tld: otheruser
share|improve this question
up vote 9 down vote accepted

The easiest way is to set the field separator to ":"

awk -F":" '$2~/user/{print $1}' /etc/userdomains

And if you want to check for exact username, 

awk -F"[ \t]*:[ \t]*" '$2=="user"{print $1}' /etc/userdomains
share|improve this answer
What's the $2~ part about? – kizzx2 Oct 24 '10 at 18:27
@kizzx2: A bare /user/ is like $0 ~ /user/$2 ~ /user/ means "does $2 match /user/"? Also, if the string user can vary depending on input, be sure to use -v to avoid having to deal with quoting issues, e.g. awk -v "user=$USER" '$2==user{print$1}'. – ephemient Oct 24 '10 at 20:11

awk has a sub(regexp, replacement, target) function that finds the first occurrence of regexp in target ($0 by default) and replaces it with replacement (in-place):

awk '/user/ {sub(/:/, ""); print $1}' /etc/userdomains
share|improve this answer

You can use gsub in awk to remove all :s in the string.

awk '/user/ {gsub(":", ""); print $1}' /etc/userdomains
share|improve this answer
no need to use the extra brackets in /(user)/ . Just /user/ will do – user1606 Oct 24 '10 at 4:25
@user: Right, no idea how those got there. – sepp2k Oct 24 '10 at 10:44

You could use tr instead of sed:

awk '/user/ {print $1 }' /etc/userdomains | tr -d ":"

Though I don't see how that's better than just using awk (nor do I see what's wrong with sed).

share|improve this answer
There's no point using tr, since i believe OP wants to get rid of extra commands. Just one awk command does the job. – user1606 Oct 24 '10 at 4:23
yeah it's more of a what's the point of piping to sed when awk can do it all, and in this case I believe is more effective than sed. corrected my question to be more straightforward on that. – xenoterracide Oct 24 '10 at 4:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.