I have something in bash
like
myArray=(\'red\' \'orange\' \'green\')
And I would like to do something like
echo ${
Another tricky one-liner:
index=$((-1 + 10#0$(IFS=$'\n' echo "${my_array[*]}" | grep --line-number --fixed-strings -- "$value" | cut -f1 -d:)))
features:
-1
when not foundcaveats:
value
to be non-emptyExplanations by breaking it down in execution order:
IFS=$'\n' echo "${my_array[*]}"
set array expansion separator (IFS
) to a new line char & expand the array
grep --line-number --fixed-strings -- "$value"
grep for a match:
--line-number
or -n
)--fixed-strings
or -F
; disables regex)allow for elements starting with a -
(--
)
cut -f1 -d:
extract only the line number (format is
)
$((-1 + 10#0$(...)))
subtract 1 since line numbers are 1-indexed and arrays are 0-indexed
if $(...)
does not match:
0
is used (10#0
)$(...)
matches:
10#0
; i.e. 10#02
, 10#09
, 10#014
, etc10#
prefix forces base-10/decimal numbers instead of octalUsing awk
instead of grep
, cut
& bash arithmetic:
IFS=$'\n'; awk "\$0 == \"${value//\"/\\\"}\" {print NR-1}" <<< "${my_array[*]}"
features:
caveats:
when not foundExplanations by breaking it down in execution order:
IFS=$'\n' [...] <<< "${my_array[*]}"
set array expansion separator (IFS
) to a new line char & expand the array
awk "\$0 == \"${value//\"/\\\"}\" {print NR-1}"
match the entire line & print the 0-indexed line number
${value//\"/\\\"}
replaces double quotes in $value
with escaped versions