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.
Using Grep to Filter the Output of a CommandA command's output can be filtered with grep through piping, and only the lines matching a given pattern will be printed on the terminal. You can also chain multiple pipes in on command. As you can see in the output above there is also a line containing the grep process.
grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".
To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.
GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.
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.
You can do this with a single awk
invocation:
awk -v me=$(whoami) -F: '$1==me{print NR}' /etc/passwd
In more detail:
-v
creates an awk
variable called me
and populates it with your user name.-F
sets the field separator to :
as befits the password file.$1==me
only selects lines where the first field matches your user name.print
outputs the record number (line).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With