【问题标题】:Source grep expression from array来自数组的源 grep 表达式
【发布时间】:2019-03-22 20:17:51
【问题描述】:

我将输入从先前声明的包含多行的变量传递给 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 条件的参数? 随着我有更多的论点,可读性和可管理性下降。

【问题讨论】:

  • 如果行是连续的并且正在使用 GNU grep,请查看 grep --help 中的上下文控制以获取 n 行上下文,也许更合适

标签: bash grep


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多