将行分隔的grep结果放入数组 [英] Put line seperated grep result into array

查看:578
本文介绍了将行分隔的grep结果放入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下grep命令

echo v1.33.4 |  egrep -o '[0-9]{1,3}'

返回:

1
33
4

在Bash脚本中,我想要将那些行分隔的数字放入数组中。
我尝试将其直接分配给变量并对其运行for循环。但是循环中的回声只会产生第一个数字 1

In Bash-Script I'd like to but those line seperated numbers into an array. I tried to assign it directly to a variable and run a for loop over it. But the echo within the loop only yields the first number 1

推荐答案

这个问题的答案


如何将行存储到数组中?

how to store lines into an array?

在Bash≥4的情况下,使用 mapfile 像这样:

With Bash≥4, use mapfile like so:

mapfile -t array < <(echo "v1.33.4" |  egrep -o '[0-9]{1,3}')

使用Bash< 4时,使用循环:

With Bash<4, use a loop:

array=()
while read; do
    array+=( "$REPLY" )
done < <(echo "v1.33.4" |  egrep -o '[0-9]{1,3}')

或使用单个 read 语句:

IFS=$'\n' read -r -d '' -a array < <(echo "v1.33.4" |  egrep -o '[0-9]{1,3}')

(但请注意,返回代码为 1 )。

(but note that the return code is 1).

解决(我相信是)您的实际问题:

Answer to solve (what I believe is) your actual problem:

您有一个变量,用于存储字符串 v1。 33.4 ,并且您想要一个包含数字 1 33 和<$的数组c $ c> 4 :使用以下命令:

You have a variable where you stored the string v1.33.4 and you want an array that will contain the numbers 1, 33 and 4: use the following:

string=v1.33.4
IFS=. read -ra array <<< "${string#v}"

您根本不需要外部工具。

You don't need external utilies at all for that.

另一种可能性(也将验证字符串的格式,因此我认为这是最适合您的选择)是使用正则表达式:

Another possibility (that will also validate the format of the string, so I'd say it's the best option for you) is to use a regex:

string=v1.33.4
if [[ "$string" =~ ^v([[:digit:]]+)\.([[:digit:]]+)\.([[:digit:]]+)$ ]]; then
    array=( "${BASH_REMATCH[@]:1}" )
else
    echo >&2 "Error, bad string format"
    exit 1
fi






然后,在字段上循环


Then, to loop on the fields of the array:

for field in "${array[@]}"; do
    echo "$array"
done

这篇关于将行分隔的grep结果放入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆