string manipulation
8 methodsBash parameter expansion operators for measuring, slicing and replacing text in variables.
${#var}Returns the length of the variable's value in characters.
Returns
integer
Example
var="Hello, World"
echo ${#var} # 12
empty=""
echo ${#empty} # 0${var:offset:length}Extracts a substring starting at offset (0-based) with the given length. Omit length for to-end.
Parameters
| Name | Type | Description |
|---|---|---|
| offset | integer | Start position (negative counts from end). |
| length | integer | Number of characters (optional). |
Returns
string
Example
var="Hello, World"
echo ${var:0:5} # Hello
echo ${var:7} # World
echo ${var: -5} # World (note space before -)${var/old/new}Replaces the first match of old (glob pattern) with new in var's value.
Parameters
| Name | Type | Description |
|---|---|---|
| old | pattern | Glob pattern to match. |
| new | string | Replacement string. |
Returns
string
Example
var="a-b-c"
echo ${var/-/_} # a_b-c (only first)${var//old/new}Replaces all matches of old (glob pattern) with new in var's value.
Parameters
| Name | Type | Description |
|---|---|---|
| old | pattern | Glob pattern to match. |
| new | string | Replacement string. |
Returns
string
Example
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}Removes the shortest match of prefix from the beginning of var's value.
Parameters
| Name | Type | Description |
|---|---|---|
| prefix | pattern | Glob pattern to remove from the front. |
Returns
string
Example
path="/usr/local/bin"
echo ${path#/usr} # /local/bin
file="archive.tar.gz"
echo ${file#*.} # tar.gz (shortest)${var%suffix}Removes the shortest match of suffix from the end of var's value.
Parameters
| Name | Type | Description |
|---|---|---|
| suffix | pattern | Glob pattern to remove from the end. |
Returns
string
Example
file="archive.tar.gz"
echo ${file%.gz} # archive.tar
echo ${file%.*} # archive.tar (shortest from end)
echo ${file%%.*} # archive (longest from end)${var^^}Returns the value of var converted to uppercase. Requires Bash 4.0+.
Returns
string
Example
var="Hello, World"
echo ${var^^} # HELLO, WORLD${var,,}Returns the value of var converted to lowercase. Requires Bash 4.0+.
Returns
string
Example
var="Hello, World"
echo ${var,,} # hello, world