Concatenating Strings
Variables can be joined by placing them adjacent to each other.
prefix="sys"
suffix="_log"
combined="${prefix}${suffix}"
echo "$combined" # Output: sys_logExtracting Substrings by Index
Retrieve a portion of a string by specifying the starting position and length using the format ${variable:offset:length}.
text="deployment"
segment="${text:3:5}"
echo "$segment" # Output: loymeExtracting from the End
To capture characters counting backward from the string's end, use a negative offset. A space must precede the minus sign to avoid syntax errors.
identifier="server_42"
tail_part="${identifier: -2}"
echo "$tail_part" # Output: 42Removing Substrings Based on Patterns
Pattern matching allows removing text from the beginning or end of a string.
- ${variable#pattern}: Removes the shortest match from the start.
- ${variable##pattern}: Removes the longest match from the start.
- ${variable%pattern}: Removes the shortest match from the end.
- ${variable%%pattern}: Removes the longest match from the end.
path="/usr/local/bin/app.sh"
echo "${path#*/}" # Output: usr/local/bin/app.sh
echo "${path##*/}" # Output: app.sh
endpoint="api.v2.service.io"
echo "${endpoint%.*}" # Output: api.v2.service
echo "${endpoint%%.*}" # Output: apiReplacing Patterns
Substitute matched text with new values. Globbing meta-characters like * and ? are permitted in patterns.
- ${variable/pattern/replacement}: Replaces the first occurrence.
- ${variable//pattern/replacement}: Replaces all occurrences.
- ${variable/#pattern/replacement}: Replaces a match at the beginning.
- ${variable/%pattern/replacement}: Replaces a match at the end.
record="user:admin:role:admin"
echo "${record/admin/guest}" # Output: user:guest:role:admin
echo "${record//admin/guest}" # Output: user:guest:role:guest
echo "${record/#user/system}" # Output: system:admin:role:admin
echo "${record/%admin/root}" # Output: user:admin:role:rootDeleting Patterns
Omitting the replacement string deletes the matched text.
record="user:admin:role:admin"
echo "${record/admin}" # Output: user::role:admin
echo "${record//admin}" # Output: user::role:
echo "${record/#user}" # Output: :admin:role:admin
echo "${record/%admin}" # Output: user:admin:role:Case Conversion
Switch the entire string between uppercase and lowercase.
- ${variable^^}: Converts all characters to uppercase.
- ${variable,,}: Converts all characters to lowercase.
val="config"
echo "${val^^}" # Output: CONFIG
VAL="TEMPORARY"
echo "${VAL,,}" # Output: temporary