Bash String Operations
String operations read facts about text or build new text from it. Bash performs them inside ${ }, which is called parameter expansion.
Count the characters
The # inside the braces asks for the length of the value. The word banana has six letters, so the count is 6.
word="banana"
echo ${#word}Take the first characters
The numbers after the colon set the start position and the length. Starting at position 0 and taking four characters gives note.
word="notebook"
echo ${word:0:4}Replace the first match
The part before the second slash is the text to find. The part after it is the replacement, so world becomes bash.
message="hello world"
echo ${message/world/bash}Example
phrase="hello world"
echo ${#phrase}
echo ${phrase:0:5}
echo ${phrase/world/bash}Key points
- Parameter expansion reads or changes a variable value inside ${ }.
- Writing ${#name} gives the number of characters in the value.
- Writing ${name:0:4} takes four characters starting at position 0.
- Positions count from 0, so position 0 is the first character.
- Writing ${name/world/bash} replaces the first match of world with bash.
- These operations read the value and leave the stored text unchanged.
In this example, the first line stores hello world in the variable phrase. The first echo prints its length, which is 11 characters including the space. The second echo takes five characters from position 0 and prints hello. The last echo replaces world with bash and prints hello bash.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
The variable word holds computer. What does echo ${word:0:3} print?