Skip to content

Bash string manipulation API

Bash 索引数组 —— 一维、稀疏、以整数索引的字符串集合。

1 class · 8 methods

数组

8 methods

Bash 索引数组操作:声明、访问、迭代和切片。

${#var}

通过赋值一个用括号括起来的值列表来声明索引数组。

Returns

integer

Example

bash
var="Hello, World"
echo ${#var}  # 12

empty=""
echo ${#empty}  # 0
${var:offset:length}

返回给定整数索引(从 0 开始)处的元素。

Parameters

NameTypeDescription
indexinteger从 0 开始的索引。
lengthintegerNumber of characters (optional).

Returns

string

Example

bash
var="Hello, World"
echo ${var:0:5}    # Hello
echo ${var:7}      # World
echo ${var: -5}    # World (note space before -)
${var/old/new}

展开为数组的所有元素,作为独立的带引号单词。使用 [*] 可作为单个单词。

Parameters

NameTypeDescription
oldpatternGlob pattern to match.
newstringReplacement string.

Returns

string

Example

bash
var="a-b-c"
echo ${var/-/_}  # a_b-c (only first)
${var//old/new}

返回数组中已赋值元素的数量(不是最高索引)。

Parameters

NameTypeDescription
oldpatternGlob pattern to match.
newstringReplacement string.

Returns

string

Example

bash
var="a-b-c"
echo ${var//-/_}  # a_b_c (all matches)

path="/usr/local/bin"
echo ${path//\//_}  # _usr_local_bin (escape / in pattern)
${var#prefix}

将一个或多个元素追加到现有索引数组的末尾。

Parameters

NameTypeDescription
elementspattern要追加的值。

Returns

string

Example

bash
path="/usr/local/bin"
echo ${path#/usr}  # /local/bin

file="archive.tar.gz"
echo ${file#*.}  # tar.gz (shortest)
${var%suffix}

移除给定索引处的元素。数组变为稀疏的;索引不会移动。

Parameters

NameTypeDescription
indexpattern要移除元素的索引。

Returns

string

Example

bash
file="archive.tar.gz"
echo ${file%.gz}   # archive.tar
echo ${file%.*}    # archive.tar (shortest from end)
echo ${file%%.*}   # archive (longest from end)
${var^^}

返回从索引 start 开始的 count 个元素的切片。

Returns

string

Example

bash
var="Hello, World"
echo ${var^^}  # HELLO, WORLD
${var,,}

Returns the value of var converted to lowercase. Requires Bash 4.0+.

Returns

string

Example

bash
var="Hello, World"
echo ${var,,}  # hello, world