bash - 是否可以使用存储在数组中的关键字进行 grep?

标签 bash shell grep

是否可以使用存储在数组中的关键字进行 grep。

这是可能的代码片段;我该如何纠正它?

args=("key1" "key2" "key3")

cat file_name |while read line
 echo $line | grep -q -w ${args[c]}
done

目前,我只能搜索一个关键字。我想搜索存储在 args 数组中的所有关键字。

最佳答案

args=("key1" "key2" "key3")
pat=$(echo ${args[@]}|tr " " "|")
grep -Eow "$pat" file

或者用 shell

args=("key1" "key2" "key3")
while read -r line
do
    for i in ${args[@]}
    do
        case "$line" in
            *"$i"*) echo "found: $line";;
        esac
    done
done <"file"

关于bash - 是否可以使用存储在数组中的关键字进行 grep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2295361/

相关文章:

Bash 语法错误 : "[[: not found"

java - 使用 shell 和 Java 读写串口

shell - 在 awk 中修剪字符串的前导和尾随空格

linux - grep 精确匹配

linux - 带有空白字符的 bash 环境变量。 cd 不带引号

linux - 将 bash 脚本嵌入到 makefile 中

bash - macOS:更改 bash 的语言

windows - 像打开文本文件一样打开文件(即使其扩展名不是 .txt)

ubuntu - grep 子目录并保存多个输出

bash - grep for period=N while N 比 X 长,这句话的位置在行与行之间发生变化