I want to grab specific users ID from the /etc/passwd
file in bash.
A given user ID is made of exactly 6 characters, either 6 integers or 1 letter and 5 integers (the letter is always the first character of the user ID in the second case). See example below:
398329
y32839
392009
r39288
I am looking for a regex pattern to get a list with only the user IDs that match this format, from my /etc/passwd
file. This is what I did so far:
users="$(cut -d: -f1 /etc/passwd | grep -o '[0-9]*')"
I could get the user IDs with numbers but since my regex is limited, any help would be appreciated. Thanks!
You can use grep
with correct regex like this:
cut -d: -f1 /etc/passwd | grep -E '^[a-zA-Z0-9][0-9]{5}$'
398329
y32839
392009
r39288
^[a-zA-Z0-9][0-9]{5}$
will match username of 6 digits or a letter followed by 5 digits.
As an improvement , you can replace cut + grep
with this single awk
command:
awk -F: '$1 ~ /^[a-zA-Z0-9][0-9]{5}$/{print $1}' /etc/passwd
grep with perl regex:
grep -oP '\w:\d{5}' /etc/passwd
example results:
4:65534
x:65534
I assume you're referring to the password encrypted field in etc/passwd, which is separated with colon; but if you really only concerned with UIDs that actually begin with a letter then simply remove the second colon in the regex, '\\w\\d{5}'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.