Search code examples
bashsedawkgrepcut

Modifying grep output to have field descriptions


I am trying to write a short script to search for all users whose first name matches whatever is in names.txt

The result should be in the following example format:

Username: tom01, Full Name: Tom Bennett, Home Directory: /home/users/tom01

grep -f name.txt /etc/passwd | cut -d: -f1,5,6 | awk '{print '{"Username: "$1", Full Name: "$2", Home Directory: "$3}'

I'm pretty far from the answer here it seems, and totally stuck about which commands I should use. Any help would be massively appreciated!


Solution

  • You can skip piping to cut with something like this:

    grep -f name.txt /etc/passwd | awk -F: '{print "User name", $1, "Full name", $5, "Home directory", $6}'
    

    Note that the awk -F: '{print "User name", $1, "Full name", $5, "Home directory", $6}' uses -F: to set : as field separator and then prints the required text and data.