Print only usernames from /etc/passwd file using grep, awk or cut commands.

In this post, we will quickly check a quick tip to grep only the usernames from /etc/passwd file using grep command.

So here goes the command:

1. Using grep command

[root@nglinux ~]# cat /etc/passwd | grep -o "^[a-zA-Z_-]*" | head
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
uucp
[root@nglinux ~]# 

Understanding the grep command option:- It greps the string starting from beginning i.e. ^ which matches either alphabet a-z or capital case alphabet A-Z or the character – or underscore _, once it encounters “:” it stops and prints the greped content.

2. Using awk command
We can also perform the above task using awk command, however a bit slow since awk performs the operation line by line, field by field.

[root@nglinux ~]# cat /etc/passwd | awk -F ":" '{print $1}' | head
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
uucp
[root@nglinux ~]# 

3. Using cut command
We can also perform above task using cut command easily, like below:

[root@nglinux ~]# cat /etc/passwd | cut -d ":" -f1 | head
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
uucp
[root@nglinux ~]# 

Here we have shown some of the ways we can perform the above task, however there are number of ways to achieve same thing in linux bash programming.

I hope you liked the above tip, do post here your comments.

Leave a Reply

avatar
  Subscribe  
Notify of