首页 > 解决方案 > 来自数组的源 grep 表达式

问题描述

我将输入从先前声明的包含多行的变量传递给 grep。我的目标是只提取某些行。当我增加 grep 中的参数计数时,可读性会下降。

var1="
_id=1234
_type=document
date_found=988657890
whateverelse=1211121212"


echo "$var1"

_id=1234
_type=document
date_found=988657890
whateverelse=1211121212


grep -e 'file1\|^_id=\|_type\|date_found\|whateverelse' <<< $var1
_id=1234
_type=document
date_found=988657890
whateverelse=1211121212

我的想法是从数组传递参数,它会增加可读性:

declare -a grep_array=(
"^_id=\|"
"_type\|"
"date_found\|"
"whateverelse"
)

echo ${grep_array[@]}
^_id=\| _type\| date_found\| whateverelse


grep -e '${grep_array[@]}' <<<$var1

---- no results

如何使用 grep 从其他地方而不是一行传递具有多个 OR 条件的参数?随着我有更多的论点,可读性和可管理性下降。

标签: bashgrep

解决方案


你的想法是对的,但你在逻辑上有几个问题。type 的数组扩展将数组${array[@]}的内容作为单独的单词,由空格字符分隔。当您想将单个正则表达式字符串传递给grep时,shell 已将数组扩展为其组成部分并尝试将其评估为

grep -e '^_id=\|' '_type\|' 'date_found\|' whateverelse

这意味着您的每个正则表达式字符串现在都被评估为文件内容而不是正则表达式字符串。

因此,grep要将整个数组内容视为单个字符串,请使用${array[*]}扩展。由于这种特定类型的扩展使用字符来连接数组内容,因此如果不重置IFS,您会在单词之间获得一个默认空格(默认值)。IFS下面的语法重置IFS子shell中的值并打印出扩展的数组内容

grep -e "$(IFS=; printf '%s' "${grep_array[*]}")" <<<"$str1"

推荐阅读