2010-04-05 44 views
9

我想將一個正則表達式結果賦值給bash腳本中的一個數組,但我不確定這是否可能,或者如果我完全錯了。下面的是我希望發生的,但是我知道我的語法不正確:bash:將grep正則表達式結果分配給數組

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

這樣的:

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

的任何鏈接,或建議,將是美好:)

回答

27

這裏

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

精彩 - 正是我需要的 - 謝謝! – Ryan 2010-04-05 02:27:25

2

這裏是一個純粹的慶典方式,沒有外部命令需要

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

輸出

$ ./shell.sh 
b5f1e7bf c2439c62 1353d1ce 0629fb8b 
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