反引号中管道的使用 [英] Use of pipes in backticks
问题描述
我正在尝试使用管道运行命令,但收到错误:
I'm trying to run a command with a pipe but receive errors:
echo abc | `echo "grep a | grep b"`
grep: |: No such file or directory
grep: grep: No such file or directory
grep: b: No such file or directory
代码有什么问题?
预期的结果是要执行以下命令:
Expected results is for the following command to be executed:
echo abc | grep a | grep b
结果
abc
推荐答案
目前尚不清楚您要做什么,但这是您在做什么:
It's not clear what you are trying to do, but here is what you are doing:
echo "grep a | grep b"
输出字符串 grep a |grep b
.
这是反引号的输出.您在外壳需要命令的位置使用反引号,因此"grep'a''|'尝试将'grep''b'作为命令行使用,所有标记均按字面解释(我希望添加单引号使它更清晰一些),因此shell会忽略 echo
的输入,并且而是尝试在命名文件中查找正则表达式 a
.您显然没有名为"|","grep"或"b"的文件,因此会收到错误消息.
This is the output from the backticks. You are using the backticks in a position where the shell wants a command, so "grep 'a' '|' 'grep' 'b'" is attempted as the command line, with all the tokens interpreted literally (I added single quotes to make this a bit clearer, hopefully) so the shell ignores the input from echo
and instead attempts to look for the regular expression a
in the named files. You apparently have no files named "|", "grep", or "b", so you get an error message.
您可能想要的是
echo abc | grep a | grep b
会在"echo"的输出中搜索"a",然后在第一个grep的输出中搜索"b".因为 abc
匹配正则表达式 a
,所以第一个 grep
成功,因此将打印匹配的行;并且因为它也与正则表达式 b
匹配,所以它也会由最终的 grep
打印.
which searches for "a" in the output from "echo", then searches for "b" in the output from the first grep. Because abc
matches the regular expression a
, the first grep
succeeds, so the matching line is printed; and because it also matches the regular expression b
it is printed by the final grep
as well.
要对此进行扩展,请尝试以下操作:
To expand a bit on this, try the following:
sh$ echo abc; echo bcd; echo xya
abc
bcd
xya
sh$ ( echo abc; echo bcd; echo xya ) | grep a # print lines matching a
abc
xya
sh$ (echo abc; echo bcd; echo xya ) | grep a | grep b # print lines matching a and b
abc
不清楚为什么要使用反引号;如果这不是您要实现的目标,请更详细地说明您要实现的目标.
It is not clear why you are using backticks; if this is not what you are trying to achieve, please explain in more detail what you want to accomplish.
如果要查找与a或b匹配的行,请尝试以下操作:
If you want to find lines matching either a or b, try this:
sh$ ( echo abc; echo bcd; ) | grep '[ab]'
这篇关于反引号中管道的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!