Alex Rivera | Logout

Bash: grep pattern from command output

Asked 2012-04-23T12:52:48.150
35

I'm really new with bash, but it's one of the subjects on school. One of the exercises was:

Give the line number of the file "/etc/passwd" where the information about your own login is.

Suppose USERNAME is my own login ID, I was able to do it perfectly in this way:

 cat /etc/passwd -n | grep USERNAME | cut -f1

Which simply gave the line number required (there may be a more optimised way). I wondered however, if there was a way to make the command more general so that it uses the output of whoami to represent the grep pattern, without scripting or using a variable. In other words, to keep it an easy-to-read one-line command, like so:

 cat /etc/passwd -n | grep (whoami) | cut -f1

Sorry if this is a really noob question.

Edit
Report

1 Answer

14

You can do this with a single awk invocation:

awk -v me=$(whoami) -F: '$1==me{print NR}' /etc/passwd

In more detail:

  • the -v creates an awk variable called me and populates it with your user name.
  • the -F sets the field separator to : as befits the password file.
  • the $1==me only selects lines where the first field matches your user name.
  • the print outputs the record number (line).
answered 2012-04-23T13:03:12.837

Your Answer