If you don't mind the colon being selected too, then use:
grep -o -e ':[^:]*$' /etc/passwd
That selects a colon not followed by any other colon and then end of line and only print what matches.
If you don't want the colon and you do have a PCRE-enabled grep
, look at Regex lookahead for 'not followed by' in grep
?; you'll need to adapt it to do look-behind instead of look-ahead, that's all.
If you don't have grep
with -o
, use sed
instead (omitting the colon):
sed -n -e '/.*:\([^:]*\)$/ s//\1/p' /etc/passwd
This is probably the most portable solution.
(On macOS Sierra, and Mac OS X, the /etc/passwd
file has comment lines at the top starting with a #
. The sed
command does not print those lines because they don't have any colons on them. This works cleanly on Macs as well as Linux and other variants of Unix, therefore. It uses no advanced (aka non-portable) features of sed
.)