Bash: grep pattern from command exit

I am really new with bash, but this is one of the subjects at school. One exercise was:

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

Assuming USERNAME is my own login ID, I was able to do this completely like this:

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

Which just gave the required line number (there might be a more optimized way). However, I wondered if there was a way to make the command more general so that it uses the whoami output to represent the grep template, without scripting or using a variable . In other words, to make it easy to read with a single-line command, for example:

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

Sorry if this is really a noob question.

+6
source share
3 answers
 cat /etc/passwd -n | grep `whoami` | cut -f1 

Surrounding the command in the methods, it executes the command and sends the output to the command that it wrapped.

+16
source

You can do this with a single awk call:

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

More details:

  • -v creates an awk variable called me and populates it with the username.
  • -F sets the field separator to : according to the password file.
  • $1==me selects only lines where the first field matches your username.
  • print prints the record number (string).
+10
source

Check command substitution on the bash manual page.

You can return the ticks `` or $() , and personally I prefer the latter.

So for your question:

 grep -n -e $(whoami) /etc/passwd | cut -f1 -d : 

will substitute whoami output as an argument to the -e flag of grep , and the output of the entire command will be the line number in /etc/passwd working user.

+9
source

Source: https://habr.com/ru/post/913929/


All Articles