14.2.3 Extracting characters and ranges from strings

Preprocessor Macros: mbfl_string_idx (VAR, EXPR)
Preprocessor Macros: mbfl_string_qidx (VAR, EXPR)

Rexpectively expand into the expressions:

mbfl_string_idx(VAR, EXPR)  → ${VAR:EXPR:1}
mbfl_string_qidx(VAR, EXPR) → "${VAR:EXPR:1}"

which evaluates to the character at index EXPR in the string in the variable VAR.

Preprocessor Macro: mbfl_string_last_char (VAR)

Expand into the expression:

${$1:$((${#$1} - 1)):1}

which, if it is not empty, evaluates to the last character of the string in the variable VAR; if the string empty: the result of the evaluation is the empty string.

Usage examples:

{
  local STR='ciao'
  test 'o' = mbfl_string_last_char(STR)
}
⇒ 0

{
  local STR=$'ciao\n'
  test $'\n' = "mbfl_string_last_char(STR)"
}
⇒ 0

{
  local -r STR=
  test '' = "mbfl_string_last_char(STR)"
}
⇒ 0
Function: mbfl_string_index STRING INDEX
Function: mbfl_string_index_var _RV STRING INDEX

Select a character from a string. Echo to stdout the selected character. If the index is out of range: the empty string is echoed to stdout, that is: a newline is echoed to stdout.

The function variant _var stores the result in the variable _RV, rather than print it; Result variables.

mbfl_string_index abcdefghilm  0        -| a
mbfl_string_index abcdefghilm  4        -| e
mbfl_string_index abcdefghilm 10        -| m
mbfl_string_index abcdefghilm 11        -| <empty string>

local _RV
mbfl_string_index_var _RV abcdefghilm 0
"$_RV" ⇒ a
Function: mbfl_string_range STRING BEGIN
Function: mbfl_string_range STRING BEGIN END
Function: mbfl_string_range_var _RV STRING BEGIN
Function: mbfl_string_range_var _RV STRING BEGIN END

Extract a range of characters from a string. Arguments: STRING, the source string; BEGIN, the index of the first character in the range; END, optional, the index of the character past the last in the range, this character is not extracted.

END defaults to the string length; if the parameter END is set to the lowercase string end or the uppercase string END: the end index is set to the string length.

Echo to stdout the selected range of characters, which may be the empty string.

The function variant _var stores the result in the variable _RV, rather than print it; Result variables.

mbfl_string_range abcdefghilm 0 end     -| abcdefghilm
mbfl_string_range abcdefghilm 0         -| abcdefghilm
mbfl_string_range abcdefghilm 0 4       -| abcd
mbfl_string_range abcdefghilm 4 end     -| efghilm

local _RV
mbfl_string_range_var _RV abcdefghilm 4 end
"$_RV" ⇒ efghilm

This document describes version 3.0.0-devel.9 of Marcos Bash Functions Library.