I am wondering if there is a simple solution (one line command of sed or awk) of finding index by content in bash. For example, array=(a b c d e), given a target element "d", how can I get its corresponding array index of 3 without looping through the array and comparing each element with the target?
Asked
Active
Viewed 45 times
1 Answers
1
Try this with GNU grep:
array=(a b c d e)
declare -p array | grep -Po '\[\K[^\]](?=\]="d")'
or with sed:
array=(a b c d e)
declare -p array | sed 's/.*\[\([^\[]\)\]\+="d".*/\1/'
Output with grep and sed:
3
With a variable:
array=(a b c d e)
target="d"
index="$(declare -p array | grep -Po '\[\K[^\]](?=\]="'"$target"'")')"
echo "$index"

Cyrus
- 84,225
- 14
- 89
- 153
-
Thank you so much! Would you mind explain a little bit about the regular expression? – Zhihao_Li Jan 26 '16 at 18:58
-
Sorry, that would go beyond the scope. I suggest: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858) – Cyrus Jan 26 '16 at 20:27