Bash: grep pattern from command output

后端 未结 3 509
南旧
南旧 2021-02-05 07:17

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 informat

相关标签:
3条回答
  • 2021-02-05 07:53
    cat /etc/passwd -n | grep `whoami` | cut -f1 
    

    Surrounding a command in ` marks makes it execute the command and send the output into the command it's wrapped in.

    0 讨论(0)
  • 2021-02-05 07:54

    Check command substitution in the bash man page.

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

    So for your question:

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

    will substitute the output of whoami as the argument for the -e flag of the grep command and the output of the whole command will be line number in /etc/passwd of the running user.

    0 讨论(0)
  • 2021-02-05 07:57

    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).
    0 讨论(0)
提交回复
热议问题