Grep 多个 bash 参数 [英] Grep multiple bash parameters

查看:21
本文介绍了Grep 多个 bash 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 bash 脚本,它将在多个文件中进行搜索.

I'm writing a bash script which shall search in multiple files.

我遇到的问题是我无法将不确定数量的变量作为参数传递给 bash 脚本

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

对第一个做一个 grep,然后用其余的 egrep 结果:

Do a grep on the first one, and egrep the result with the rest:

grep "A" * | egrep B | egrep C

我试图做的是用 egreps 构建一个字符串:

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"

但不知何故这行不通,似乎 bash 没有将egrep"字符串视为 egrep.

But somehow that won't work, it seems like bash is not treating the "egrep" string as an egrep.

你们有什么建议吗?

顺便说一句,作为旁注,我无法创建任何辅助文件,因此我猜 grep -f 超出了范围.另请注意,传递给 bash 脚本的参数数量是可变的,因此我无法执行 egrep "$2" |egrep "$3".

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".

提前致谢.

费尔南多

推荐答案

一个安全的 eval 可能是一个很好的解决方案

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

运行:

bash script.sh A B C

这篇关于Grep 多个 bash 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆