Bash 来自数组的源grep表达式

Bash 来自数组的源grep表达式,bash,grep,Bash,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=\|_ty

我将先前声明的包含多行的变量的输入传递给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从其他地方(而不是一行)传递具有多个或多个条件的参数?
由于我有更多的论据,可读性和可管理性下降

你的想法是对的,但你在逻辑上有两个问题。${array[@]}类型的数组扩展将数组的内容作为单独的字,由空格字符分割。当您希望将单个regexp字符串传递给grep时,shell已将数组扩展为其组成部分,并尝试将其计算为

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
grep -e '^_id=\|' '_type\|' 'date_found\|' whateverelse
这意味着每个regexp字符串现在都作为文件内容而不是regexp字符串进行计算

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

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

如果行是连续的并且使用GNUGREP,请查看grep中的上下文控制-帮助获取n行上下文,可能更合适