13

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:

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 :)

3 Answers 3

35

here

array=( $(echo b5f1e7bfc2439c621353d1ce0629fb8b | grep -o '[a-f0-9]\{8\}') )
$ echo ${array[@]}
b5f1e7bf c2439c62 1353d1ce 0629fb8b
Sign up to request clarification or add additional context in comments.

Comments

4
#!/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

Comments

2

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

#!/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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.