nateph nateph - 3 months ago 18
Bash Question

Use grep and cut to filter text file to only display usernames that start with ‘m’ ‘w’ or ‘s’ and their home directories

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
sys:x:3:1:sys:/dev:/usr/sbin/nologin
games:x:5:2:games:/usr/games:/usr/sbin/nologin
mail:x:8:5:mail:/var/mail:/usr/sbin/nologin
www-data:x:33:3:www-data:/var/www:/usr/sbin/nologin
backup:x:34:2:backup:/var/backups:/usr/sbin/nologin
nobody:x:65534:1337:nobody:/nonexistent:/usr/sbin/nologin
syslog:x:101:1000::/home/syslog:/bin/false
whoopsie:x:109:99::/nonexistent:/bin/false
user:x:1000:1000:edco8700,,,,:/home/user:/bin/bash
sshd:x:116:1337::/var/run/sshd:/usr/sbin/nologin
ntp:x:117:99::/home/ntp:/bin/false
mysql:x:118:999:MySQL Server,,,:/nonexistent:/bin/false
vboxadd:x:999:1::/var/run/vboxadd:/bin/false


this is an /etc/passwd file I need to do this command on. So far I have:

cut -d: -f1,6 testPasswd.txt | grep ???


that will display all the usernames and the folder associated, but I'm stuck on how to find only the ones that start with m,w,s and print the whole line.

I've tried
grep -o '^[mws]*'
and different variations of it, but none have worked.

Any suggestions?

Answer

Try variations of

cut -d: -f1,6 testPasswd.txt | grep '^m\|^w\|^s' 

Or to put it more concisely,

cut -d: -f1,6 testPasswd.txt | grep '^[mws]'

That's neater especially if you have a lot of patterns to match.

But of course the awk solution is much better if doing it without constraints.