6
awk '/user/ {print $1 }' /etc/userdomains | sed 's/://'

the format of /etc/userdomains is

domain.tld: user
otherdomain.tld: otheruser
9

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
  • 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
2

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
2

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

awk '/user/ {gsub(":", ""); print $1}' /etc/userdomains
  • 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
1

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).

  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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