Reputation: 13
All the users in the system
that dosen't have as an ending character on their names a, s, t, r, m, z must be shown in Bash.
The users names can be obtained from the /etc/passwd
file, in the first column. But I can not perceive the correct approach to exclude those characters from the search.
Should I use grep? Or just a cut?
Upvotes: 1
Views: 399
Reputation: 52529
Something like
grep -o '^[^:]*[^astrmz:]:' /etc/passwd | tr -d :
or
cut -d: -f1 /etc/passwd | grep '[^astrmz]$'
[^blah]
matches any character but the ones listed, the opposite of [blah]
.
GNU grep
using a lookahead:
grep -Po '^[^:]*[^astrmz:](?=:)' /etc/passwd
Or using awk
instead:
awk -F: '$1 ~ /[^astrmz]$/ { print $1 }' /etc/passwd
Or in pure bash
without external commands:
while IFS=: read -r name rest; do
if [[ $name =~ [^astrmz]$ ]]; then
echo "$name"
fi
done < /etc/passwd
As you can see, there's lots of potential approaches.
Upvotes: 3
Reputation: 2610
Simple one liner when using bash
:
compgen -u | grep -v '[astrmz]$'
The compgen -u
command will produce a list of users (without all of the extra fields present in /etc/passwd
); compgen
is a builtin in bash
where it's normally used for username completion.
Upvotes: 1
Reputation: 2534
This should do the trick:
cut -d: -f1 /etc/passwd | grep -vE 's$|t$|r$|m$|z$'
The cut command strips out the username from the password file. Then grep -v (does the UNMATCHING) grep -E does multiple matching (OR OR OR) the $ sign indicates the last character to match
For example , on my mac, I get:
_gamecontrollerd
_ondemand
_wwwproxy
_findmydevice
_ctkd
_applepay
_hidd
_analyticsd
_fpsd
_timed
_reportmemoryexception
(You see no names end with those 5 letters).
Good Luck.
Upvotes: 0