简体   繁体   English

Bash:来自命令输出的grep模式

[英]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: 更详细:

  • the -v creates an awk variable called me and populates it with your user name. -v创建一个名为meawk变量,并用您的用户名填充它。
  • the -F sets the field separator to : as befits the password file. -F将字段分隔符设置为:适合密码文件。
  • the $1==me only selects lines where the first field matches your user name. $1==me只选择第一个字段与您的用户名匹配的行。
  • the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM