如何将 grep/git grep 与管道输出一起使用?

问题描述

是否可以使用管道输出作为 grep 或 git grep 的输入?我试图传递给 grep/git grep 的数据如下

    kubectl get namespace -o name -l app.kubernetes.io/instance!=applications | cut -f2 -d "/" 
argocd
default
kube-node-lease
kube-public
kube-system
nsx-system
pks-system

我试图扩展命令,但这会导致错误

   kubectl get namespace -o name -l app.kubernetes.io/instance!=applications | cut -f2 -d "/" | xargs git grep -i
fatal: ambiguous argument 'default': unkNown revision or path not in the working tree.
Use '--' to separate paths from revisions,like this:
'git <command> [<revision>...] -- [<file>...]'

仅使用 grep 结果:

    kubectl get namespace -o name -l app.kubernetes.io/instance!=applications | cut -f2 -d "/" | xargs grep -i
grep: default: No such file or directory
grep: kube-node-lease: No such file or directory
grep: kube-public: No such file or directory
grep: kube-system: No such file or directory
grep: nsx-system: No such file or directory
grep: pks-system: No such file or directory

在这种特殊情况下,我通常使用 grep 面临的问题是,即使我只在我的目录中使用 grep,它也需要很长时间才能完成,而 git grep 在几秒钟内完成。如果我没有做一些可怕的错误来解释 grep 结果缓慢,那么最好让 git grep 工作。

我发现另一个 Stackoverflow Question 可以解释问题所在,但我不知道如何正确地将输出“处理”到 git grep 中。

解决方法

问题是(如您的屏幕截图所示)结果是多个术语,我猜您想将它们OR 放在一起,而不是搜索已识别文件中的第一个术语按最后一项(这是当前的 xargs 命令所做的)

由于正则表达式中的 OR 是通过 | 字符,您可以使用 xargs echo 将垂直列表折叠成以空格分隔的水平列表,然后用 | 替换空格并非常接近到你想要的

printf 'alpha\nbeta\ncharlie\n' | xargs echo | tr ' ' '|' | xargs git grep -i

尽管由于折叠操作,该命令是一行的 xargs,因此在概念上更容易推理使用正常的 $() 插值:

git grep -i $(printf 'alpha\nbeta\ncharlie\n' | xargs echo | tr ' ' '|')

较少的“whaaa”shell 管道将使用 kubectl get -o go-template= 实际发出一个管道分隔的列表并将其提供给 xargs(或 $()),绕过对输出文本进行处理的需要先