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

时间:2016-08-01 19:20:09

标签: linux bash shell grep

我想使用--include参数传递给grep命令(在bash脚本中),搜索的文件扩展名。 这些文件扩展名将由用户从命令行输入作为参数(第四个参数保存文件扩展名,以逗号分隔的方式)。

这是我的剧本:

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

我也尝试使用命令创建一个String,并调用eval,如下所示:

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

(当回应comando时,我得到这个: egrep -irn .-- include = *。{wsdl,xml} --exclude = *。{class} -e texto ,这正是commando如果在命令行中执行,则返回一些匹配。)

我还尝试使用所有include参数传递一个变量:

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

这是从命令行调用脚本的方式:

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

关于如何实现这一目标的任何想法? 谢谢

2 个答案:

答案 0 :(得分:1)

我只是理解你遇到问题的原因:如果我复制/粘贴生成的命令,它可以工作,但是在shell中却没有。

所以我建议将其作为一种解决方法

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

(将echo传递给一个新的shell就可以了:它有效)。也许这不是最好的答案,但它确实起到了作用。

也许有人可以解释,或者提出更好,更清洁的答案。

答案 1 :(得分:1)

您没有提供任何样本输入或预期输出,因此这显然未经测试,但正确的方法是使用find查找文件,将grep用于 G 在文件中搜索 R egular E xpression,并在 P 中搜索匹配文本(请参阅其中的提示)名字;-))。类似的东西:

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

man find,xargs和grep了解详情。

相关问题