String manipulation

Authors

Marie-Hélène Burle

Alex Razoumov

This section shows how to subset, search, replace, or concatenate strings simply using the Bash variable extraction syntax.

Getting a subset

var="hello"
echo ${var:2}      # Print from character 2
echo ${var:2:1}    # Print 1 character from character 2
llo
l

Bash indexes from 0.

Search and replace

var="hello"
echo ${var/l/L}    # Replace the first match of l by L
echo ${var//l/L}   # Replace all matches of l by L
heLlo
heLLo

String concatenation

If you want to concatenate the expanded variable with another string, you need to use curly braces or quotes.

This does not return anything because there is no variable called varshine:

var=sun
echo $varshine

These two syntaxes do work:

var=sun
echo ${var}shine
echo "$var"shine
sunshine
sunshine