bash:将 grep 正则表达式结果分配给数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2576622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:54:40  来源:igfitidea点击:

bash: assign grep regex results to array

regexbasharrays

提问by Ryan

I am trying to assign a regular expression result to an array inside of a bash script but I am unsure whether that's possible, or if I'm doing it entirely wrong. The below is what I want to happen, however I know my syntax is incorrect:

我正在尝试将正则表达式结果分配给 bash 脚本内的数组,但我不确定这是否可能,或者我是否完全错误。下面是我想要发生的事情,但是我知道我的语法不正确:

indexes[4]=$(echo b5f1e7bfc2439c621353d1ce0629fb8b | grep -o '[a-f0-9]\{8\}')

such that:

使得:

index[1]=b5f1e7bf
index[2]=c2439c62
index[3]=1353d1ce
index[4]=0629fb8b

Any links, or advice, would be wonderful :)

任何链接或建议都会很棒:)

回答by theosp

here

这里

array=( $(echo b5f1e7bfc2439c621353d1ce0629fb8b | grep -o '[a-f0-9]\{8\}') )
$ echo ${array[@]}
b5f1e7bf c2439c62 1353d1ce 0629fb8b

回答by Paused until further notice.

#!/bin/bash
# Bash >= 3.2
hexstring="b5f1e7bfc2439c621353d1ce0629fb8b"
# build a regex to get four groups of eight hex digits
for i in {1..4}
do
    regex+='([[:xdigit:]]{8})'
done
[[ $hexstring =~ $regex ]]      # match the regex
array=(${BASH_REMATCH[@]})      # copy the match array which is readonly
unset array[0]                  # so we can eliminate the full match and only use the parenthesized captured matches
for i in "${array[@]}"
do
    echo "$i"
done

回答by ghostdog74

here's a pure bash way, no external commands needed

这是一种纯粹的 bash 方式,不需要外部命令

#!/bin/bash
declare -a array
s="b5f1e7bfc2439c621353d1ce0629fb8b"
for((i=0;i<=${#s};i+=8))
do
 array=(${array[@]} ${s:$i:8})
done
echo ${array[@]}

output

输出

$ ./shell.sh
b5f1e7bf c2439c62 1353d1ce 0629fb8b