[英]Bash: grep pattern from command output
I'm really new with bash, but it's one of the subjects on school. 我真的很喜欢bash,但这是学校的主题之一。 One of the exercises was: 其中一项练习是:
Give the line number of the file "/etc/passwd" where the information about your own login is. 给出文件“/ etc / passwd”的行号,其中有关您自己的登录信息。
Suppose USERNAME
is my own login ID, I was able to do it perfectly in this way: 假设USERNAME
是我自己的登录ID,我能够以这种方式完美地完成:
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 . 然而,我想知道,如果有一种方法可以使命令更通用,那么它使用whoami
的输出来表示grep模式, 而无需编写脚本或使用变量 。 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. 对不起,如果这是一个真正的菜鸟问题。
cat /etc/passwd -n | grep `whoami` | cut -f1
在`标记中包含一个命令使它执行命令并将输出发送到它所包含的命令中。
You can do this with a single awk
invocation: 您可以使用单个awk
调用执行此操作:
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. -v
创建一个名为me
的awk
变量,并用您的用户名填充它。 -F
sets the field separator to :
as befits the password file. -F
将字段分隔符设置为:
适合密码文件。 $1==me
only selects lines where the first field matches your user name. $1==me
只选择第一个字段与您的用户名匹配的行。 print
outputs the record number (line). print
输出记录号(行)。 Check command substitution in the bash
man page. 检查bash
手册页中的命令替换。
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. 将whoami
的输出替换为grep
命令的-e
标志的参数,整个命令的输出将是正在运行的用户的/etc/passwd
中的行号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.