Next: , Previous: , Up: strings   [Contents][Index]


14.3 Splitting a string

Variable: SPLITFIELD

Array used by mbfl_string_chars() to store the result of splitting a string.

Variable: SPLITCOUNT

Array used by mbfl_string_chars() to store the number of values in SPLITFIELD.

Function: mbfl_string_chars string

Split a string into characters. Fill an array named SPLITFIELD with the characters from the string; the number of elements in the array is stored in a variable named SPLITCOUNT. Both SPLITFIELD and SPLITCOUNT can be declared local in the scope of the caller.

The difference between this function and using ${STRING:$i:1}, is that this function detects backslash characters, \, and treats them as part of the following character. So, for example, the sequence \n is treated as a single char.

Example of usage for mbfl_string_chars():

local SPLITFIELD
local -i SPLITCOUNT

string="abcde\nfghilm"
mbfl_string_chars "${string}"

$SPLITCOUNT             ⇒ 12
"${SPLITFIELD[0]}"    ⇒ a
"${SPLITFIELD[1]}"    ⇒ b
"${SPLITFIELD[2]}"    ⇒ c
"${SPLITFIELD[3]}"    ⇒ d
"${SPLITFIELD[4]}"    ⇒ e
"${SPLITFIELD[5]}"    ⇒ \n
"${SPLITFIELD[6]}"    ⇒ f
"${SPLITFIELD[7]}"    ⇒ g
"${SPLITFIELD[8]}"    ⇒ h
"${SPLITFIELD[9]}"    ⇒ i
"${SPLITFIELD[10]}"   ⇒ l
"${SPLITFIELD[11]}"   ⇒ m
Function: mbfl_string_split string separator

Split string into fields using separator. Fill an array named SPLITFIELD with the characters from the string; the number of elements in the array is stored in a variable named SPLITCOUNT. We can declare both SPLITFIELD and SPLITCOUNT as local in the scope of the caller.

Function: mbfl_string_split_blanks string

Split string into fields using adjacent blank characters as separators. Fill an array named SPLITFIELD with the characters from the string; the number of elements in the array is stored in a variable named SPLITCOUNT. We can declare both SPLITFIELD and SPLITCOUNT as local in the scope of the caller.

local -a SPLITFIELD
local -i SPLITCOUNT
local STRING

printf -v STRING 'abc\t \tdef\t\t ghi \t\tlmn\t \topq\t\t   rs'

mbfl_string_split_blanks "$STRING"

$SPLITCOUNT             ⇒ 6
"${SPLITFIELD[0]}"      ⇒ abc
"${SPLITFIELD[1]}"      ⇒ def
"${SPLITFIELD[2]}"      ⇒ ghi
"${SPLITFIELD[3]}"      ⇒ lmn
"${SPLITFIELD[4]}"      ⇒ opq
"${SPLITFIELD[5]}"      ⇒ rs

Next: , Previous: , Up: strings   [Contents][Index]

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