Extracting substrings

If we know a specific substring we want to extract from a variable by where it starts, and optionally how long it is, we can use the ${var:start} or ${var:start:length} form:

bash$ title='== Password =='
bash$ printf '%s\n' "${title:3}"
Password ==
bash$ printf '%s\n' "${title:3:8}"
Password

By specifying a negative start value, you can start the counting from the end of the string, starting at -1:

bash$ alpha='abcdefghijk'
bash$ printf '%s\n' "${alpha: -3:2}"
ij

Note that we had to add a space prefix before the minus sign, to prevent the shell from interpreting this as the unrelated :- form.

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.