Mastering Bash String Manipulation via Parameter Expansion

String Length Calculation and Slicing

Retrieving the character count of a variable is achieved by prefixing the variable name with a hash symbol. To slice a portion of a string, specify a starting index followed by an optional length modifeir. Indices are zero-based.

text="Automation-Script-v2"

echo "${#text}"       
echo "${text:12}"     
echo "${text:4:6}"    

Pattern Matching Deletion You can strip portions of a string based on glob patterns. The direction of traversal and the greediness of the match determine which operator to use:

  • ${var#pattern} removes the shortest prefix match.
  • ${var##pattern} removes longest prefix match.
  • ${var%pattern} removes the shortest suffix match.
  • ${var%%pattern} removes the longest suffix match.
config_path="/opt/app/config/db_settings.conf"

echo "${config_path#/opt/app/}"
echo "${config_path##/*/}"
echo "${config_path%.conf}"
echo "${config_path%%_*}"

Dynamic Replacement Strategies Substitutions allow targeted changes within a string. Operators support replacing the first occurrence, all occurrences, or strictly prefix/suffix matches.

log_message="[INFO]: system_startup detected timeout"

echo "${log_message/timeout/latency}"
echo "${log_message// /_}"
echo "${log_message/#\[INFO\]/[DEBUG]}"
echo "${log_message/%timeout/failure}"

Globbing Capabilities All pattern definitions mentioned above support standard shell globbing characters (*, ?, [...]). This allows flexible matching against dynamic paths, filenames, or structured logs during script execution.

Tags: bash shell-scripting string-manipulation parameter-expansion

Posted on Sat, 24 Oct 2026 16:52:00 +0000 by aka_bigred