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

the format of /etc/userdomains is

domain.tld: user
otherdomain.tld: otheruser
xenoterracide
  • 59,188
  • 74
  • 187
  • 252

4 Answers4

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
user1606
  • 919
  • 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

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

awk '/user/ {gsub(":", ""); print $1}' /etc/userdomains
sepp2k
  • 5,597
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
Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
0

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

frabjous
  • 8,691
  • 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 04: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 04:48