grep多个bash参数 [英] Grep multiple bash parameters
问题描述
我遇到的问题是我无法egrep数量不确定的变量作为参数传递给bash脚本
我希望它执行以下操作:
给定随机数参数。即:
./ searchline.sh ABC
对第一个做一个grep,然后用其他的方法处理结果:
grepA* | egrep B | egrep C
我试图做的是用egreps构建一个字符串:
for j in$ {@:2};
做
ADDITIONALSEARCH =$ ADDITIONALSEARCH | egrep $ j;
完成
grep$ 1*$ ADDITIONALSEARCH
但不知何故,这将无法正常工作,似乎bash不会将egrep字符串视为egrep。
你们有什么建议吗?
>顺便说一句,作为一个附注,我无法创建任何辅助文件,所以我猜grep -f不在线。还要注意,传递给bash脚本的参数数量是可变的,所以我不能做egrep$ 2| egrep$ 3。
预先感谢。
费尔南多
bin / bash
if [[$#-gt 0]];然后
TEMP =(grep-e\\ $ 1 \*)
for((I = 2; I <= $#; ++一世 ));做
TEMP =($ {TEMP [@]}|egrep-e\\ $$ {I} \)
完成
eval$ {TEMP [@]}
fi
运行它:
bash script.sh ABC
I'm writing a bash script which shall search in multiple files.
The problem I'm encountering is that I can't egrep an undetermined number of variables passed as parameters to the bash script
I want it to do the following:
Given a random number of parameters. i.e:
./searchline.sh A B C
Do a grep on the first one, and egrep the result with the rest:
grep "A" * | egrep B | egrep C
What I've tried to do is to build a string with the egreps:
for j in "${@:2}";
do
ADDITIONALSEARCH="$ADDITIONALSEARCH | egrep $j";
done
grep "$1" * "$ADDITIONALSEARCH"
But somehow that won't work, it seems like bash is not treating the "egrep" string as an egrep.
Do you guys have any advice?
By the way, as a side note, I'm not able to create any auxiliary file so grep -f is out of the line I guess. Also note, that the number of parameters passed to the bash script is variable, so I can't do egrep "$2" | egrep "$3".
Thanks in advance.
Fernando
A safe eval could be a good solution
#!/bin/bash
if [[ $# -gt 0 ]]; then
TEMP=("grep" "-e" "\"\$1\"" "*")
for (( I = 2; I <= $#; ++I )); do
TEMP=("${TEMP[@]}" "|" "egrep" "-e" "\"\$${I}\"")
done
eval "${TEMP[@]}"
fi
To run it:
bash script.sh A B C
这篇关于grep多个bash参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!