简体   繁体   English

在bash脚本中使用grep命令将变量值传递给--include参数

[英]Pass variable value to --include argument using grep command inside bash script

I want to pass to grep command (inside a bash script), the file extensions to search, using --include argument. 我想使用--include参数传递给grep命令(在bash脚本中),要搜索的文件扩展名。 These file extensions will be entered by user from command line as an argument (4th argument holds files extensions, in a comma separated way). 这些文件扩展名将由用户从命令行作为参数输入(第4个参数以逗号分隔的方式保存文件扩展名)。

This is my script: 这是我的脚本:

...
echo "Searching in ${4} files for pattern"
egrep -irn . --include=\*.{"${4}"} --exclude=\*.{class} -e "${3}"
...  

I also tried creating a String with the command, and calling eval, like this: 我还尝试使用命令创建一个String,然后调用eval,如下所示:

...
comando="egrep -irn . --include="\\*.{${4}}" --exclude=\*.{class} -e "${3}""
echo $comando
resultado=eval $comando
echo $resultado

(when echoing comando i get this: egrep -irn . --include=*.{wsdl,xml} --exclude=*.{class} -e texto , which is exactly the commando that if executed in command line returns some matches.) (当回显comando时,我得到以下信息: egrep -irn。--include = *。{wsdl,xml} --exclude = *。{class} -e texto ,这正是在命令行中执行时会返回一些匹配项的突击队)

I also tried passing a variable with all the include argument: 我还尝试通过所有include参数传递变量:

...
argumento="\\*.{${4}}"
egrep -irn . --include=$argumento --exclude=\*.{class} -e "${3}"
...

This is how the script is called from command line: 这是从命令行调用脚本的方式:

sh ./searchRecursiveIterativeEgrep.sh /tmp/test/another/ /usr/local/aux/ "texto" wsdl,xml sh ./searchRecursiveIterativeEgrep.sh / tmp / test / another / / usr / local / aux /“ texto” wsdl,xml

Any ideas on how to achieve this? 关于如何实现这一目标的任何想法? Thank you 谢谢

I just understood why you had a problem: If I copy/paste the generated command, it works but within a shell it doesn't. 我只是理解为什么会有问题:如果我复制/粘贴生成的命令,它可以工作,但在shell中却不能。

So I propose that as a workaround 因此,我建议将其作为解决方法

argumento="\\*.{${4}}"
echo egrep -irn . --include=$argumento --exclude=\*.{class} -e "${3}" | sh

(piping the echo to a new shell does it: it works). (将回显插入新的外壳即可:它可以正常工作)。 Maybe it's not the best answer but it does the job. 也许这不是最佳答案,但确实可以。

Maybe someone can explain that, or come out with a better, cleaner answer. 也许有人可以解释一下,或者给出更好,更干净的答案。

You didn't provide any sample input or expected output so this is obviously untested but the right approach is to use find to FIND files and grep to G lobally search for a R egular E xpression in a file and P rint the matching text (see the hints in their names ;-) ). 您没有提供任何样本输入或预期输出所以这显然是未经测试,但正确的方法是使用find 查找文件和grepG lobally搜索在文件和P RINT匹配的文本A R egularê上的表达(见其名称中的提示;-))。 Something like: 就像是:

find . -type f -name "*.$4" -print0 | xargs -0 grep -Ein "$3"

man find, xargs, and grep for details. 手动查找,xargs和grep了解详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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