Posted: . At: 10:23 AM. This was 5 years ago. Post ID: 12981
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


More very useful tricks with awk on Linux.


This awk example, will print all lines except those that start with a # character.

awk '!/^#/ && !/^$/ {print}'

Use it this way, instead of using cat.

4.4 Mon Mar 11 jason@Yog-Sothoth 1: $ awk '!/^#/ && !/^$/ {print}' .bashrc

This example will filter a text file and then output it to the file named ‘outfile’.

4.4 Mon Mar 11 jason@Yog-Sothoth 1: $ awk '!/^#/ && !/^$/ {print}' .bashrc > outfile

Remove all blank lines from the input stream.

jason@hoshi:/etc$ awk '!/^$/ {print}' bash.bashrc

List all users with a shell that is /bin/bash and a home directory.

jason@hoshi:/etc$ sudo awk -F":" '$7 == "/bin/bash" {print "Username: "$1 "Home Dir: "$6}' /etc/passwd
Username: rootHome Dir: /root
Username: jasonHome Dir: /home/jason

This is another way to print the same information with better formatting.

jason@hoshi:/etc$ sudo awk -F":" '$7 == "/bin/bash" {print "Username: "$1 "\nHome Dir: "$6}' /etc/passwd | perl -pe 's/\n/ : / if $.%2'
Username: root : Home Dir: /root
Username: jason : Home Dir: /home/jason

These tips should be very useful for listing information about all of your users on a Linux system.

Here is a version with better formatting.

jason@hoshi:/etc$ sudo awk -F":" '$7 == "/bin/bash" {print "Username: "$1 " Home Dir: "$6","}' /etc/passwd | perl -pe 's/\n/\n/ if $.%2'
Username: root Home Dir: /root,
Username: jason Home Dir: /home/jason,

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.