|
| From: | Léa Gris |
| Subject: | Re: efficient way to use matched string in variable substitution |
| Date: | Tue, 24 Aug 2021 16:16:46 +0200 |
| User-agent: | Telnet/1.0 [tlh] (PDP11/DEC) |
Le 24/08/2021 à 15:09, Mike Jonkmans écrivait :
This seems to be the fastest:
f12 () { [[ "$1" =~ ${1//?/(.)} ]]; local arr=( "${BASH_REMATCH[@]:1}" ); }
time for ((i=1; i<=10000; i++)); do f0 682390; done
real 0m0,296s
user 0m0,296s
sys 0m0,000s
Awesome Mike, would you like to add this answer to SO?It would be very useful there; but I don't want to be wrongly credited for this smart implementation.
time for ((i=1; i<=10000; i++)); do f12 682390; done
real 0m0.223s
user 0m0.223s
sys 0m0.000s
Made it into a fancy utility function:
string2array() {
# Splits the string's characters into the array
# $1: The input string
# $2: The output array name
[[ "$1" =~ ${1//?/(.)} ]]
# shellcheck disable=SC2178 # shellcheck broken nameref type check
local -n arr="$2"
# shellcheck disable=SC2034 # shellcheck broken nameref usage check
arr=("${BASH_REMATCH[@]:1}")
}
--
Léa Gris
| [Prev in Thread] | Current Thread | [Next in Thread] |