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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10280941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:58:22  来源:igfitidea点击:

Bash: grep pattern from command output

bashunixgreppipe

提问by MarioDS

I'm really new with bash, but it's one of the subjects on school. One of the exercises was:

我对 bash 真的很陌生,但它是学校的科目之一。其中一项练习是:

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

给出你自己登录信息所在的文件“/etc/passwd”的行号。

Suppose USERNAMEis 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 whoamito 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:

这只是给出了所需的行号(可能有更优化的方法)。但是,我想知道是否有办法使命令更通用,以便它使用 的输出whoami来表示 grep 模式,而无需编写脚本或使用变量。换句话说,要使其成为易于阅读的单行命令,如下所示:

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

Sorry if this is a really noob question.

对不起,如果这是一个非常菜鸟的问题。

回答by Lynn Crumbling

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.

用 ` 标记包围命令使其执行该命令并将输出发送到它所包含的命令中。

回答by paxdiablo

You can do this with a single awkinvocation:

您可以通过一次awk调用来做到这一点:

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

In more detail:

更详细地:

  • the -vcreates an awkvariable called meand populates it with your user name.
  • the -Fsets the field separator to :as befits the password file.
  • the $1==meonly selects lines where the first field matches your user name.
  • the printoutputs the record number (line).
  • -v创建一个awk名为变量me,并与您的用户名填充它。
  • -F设置字段分隔符:为应景密码文件。
  • $1==me只选择第一个字段匹配您的用户名线。
  • print输出的记录数(线)。

回答by Chilledrat

Check command substitution in the bashman page.

检查bash手册页中的命令替换。

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

你可以支持 tick``$(),我个人更喜欢后者。

So for your question:

所以对于你的问题:

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

will substitute the output of whoamias the argument for the -eflag of the grepcommand and the output of the whole command will be line number in /etc/passwdof the running user.

将替代输出whoami作为命令-e标志的参数,grep整个命令的输出将是/etc/passwd正在运行的用户的行号。