Last active
May 24, 2023 06:16
-
-
Save ochaloup/4d6ca93a6826a65c3f1f781d5af59d4b to your computer and use it in GitHub Desktop.
Bash script to print a subset of array
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
#!/bin/bash | |
# Usage: | |
# arraybyindex.sh <uint array> <index> <length> | |
# arraybyindex.sh '[1,2,3,4,5,6,7,8]' 4 2 | |
# Output: | |
# 5 6 | |
# - or - | |
# arraybyindex.sh '[1,2,3]' 1 1 | |
# 2 | |
isuint() { [[ $1 =~ ^[0-9]+$ ]] ;} | |
if [ $# -lt 2 ]; then | |
echo "Expecting two or three arguments that is list of uint8 numbers and index and length, like ${0} '[1,2,3]' 1 2" | |
exit 2 | |
fi | |
ARR="$1" | |
if ! isuint "$2" ; then | |
echo "Expecting the second argument being a number but it's '$2'" | |
exit 3 | |
fi | |
if [ $# -gt 2 ] && ! isuint "$3"; then | |
echo "Expecting the third argument being a number but it's '$3'" | |
exit 4 | |
fi | |
INDEX="$2" | |
[ $# -gt 2 ] && SIZE="$3" || SIZE="" | |
ARR_CONVERTED=`echo $ARR | sed 's/[,]/ /g' | sed 's/\[\|\]/ /g'` | |
ARR_BASH=( $ARR_CONVERTED ) | |
if [ 'x' == "x$SIZE" ]; then | |
OUT_ARRAY="${ARR_BASH[@]:INDEX}" | |
else | |
OUT_ARRAY="${ARR_BASH[@]:INDEX:SIZE}" | |
fi | |
OUT=`echo "[${OUT_ARRAY[@]}]" | sed 's/ /,/g'` | |
echo "$OUT" | |
[ -x "$(command -v xsel)" ] && echo -n "$OUT" | xsel -ib |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment