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=\|_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 条件的参数?随着我有更多的论点,可读性和可管理性下降。
解决方案
你的想法是对的,但你在逻辑上有几个问题。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"
推荐阅读
- hibernate - hibernate 获取底层 sql resutlset。nativequery 非常有限
- cassandra - Apache Cassandra 3.11.6:集群键错误,cass-stress 写入后表中未定义的列名
- android - Android:更正 Nexus 5 和 Pixel 3a 的尺寸值
- python - 来自 statsmodels 的自定义估计器 WLS 的 sklearn check_estimator 错误
- sentry - 哨兵在 react-native 中没有捕捉到本地粉碎
- ruby-on-rails - 缓存的 Ruby Haml 块返回空
- css - 响应式 css 网格 - 如何使第一项 2 x 宽度和响应式
- javascript - 为什么在附加到文档时会忽略某些 keydown 事件?
- elasticsearch - 在 Windows 10 中哪里可以找到 Kibana 系统日志文件
- r - 如何创建标识行值更改的另一列的列?