Created
June 5, 2018 17:43
-
-
Save miguel-amaral/668be3de284e92c4ffc1f3ea88d3b238 to your computer and use it in GitHub Desktop.
Check if element is in array bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# given the following data | |
mydata=(a b c "hello world") | |
for val in a c hello "hello world" | |
do | |
# get line # of 1st matching entry | |
ix=$( printf "%s\n" "${mydata[@]}" | grep -n -m 1 "^${val}$" | cut -d ":" -f1 ) | |
if [[ -z $ix ]] | |
then | |
echo $val missing | |
else | |
# subtract 1. Bash arrays are zero-based, but grep -n returns 1 for 1st line, not 0 | |
echo $val found at $(( ix-1 )) | |
fi | |
done | |
#### OUTPUT | |
#a found at 0 | |
#c found at 2 | |
#hello missing | |
#hello world found at 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment