String Manipulation Operations
Demonstrates Bash string manipulation including substring extraction, pattern replacement, case conversion, trimming, and splitting operations.
Code
#!/usr/bin/env bash
set -euo pipefail
str="Hello, World! Welcome to Bash."
filepath="/usr/local/bin/my-script.sh"
# Length
echo "Length: ${#str}"
# Substring extraction
echo "From 7: ${str:7}"
echo "Chars 0-5: ${str:0:5}"
echo "Last 5: ${str: -5}"
# Case conversion (Bash 4+)
echo "Upper: ${str^^}"
echo "Lower: ${str,,}"
echo "First upper: ${str^}"
# Pattern removal (prefix)
echo "Filename: ${filepath##*/}"
echo "Dir: ${filepath%/*}"
echo "No ext: ${filepath%.sh}"
echo "Ext only: ${filepath##*.}"
# Pattern substitution
sentence="The quick brown fox"
echo "Replace first: ${sentence/quick/slow}"
echo "Replace all: ${sentence//o/0}"
echo "Replace prefix: ${sentence/#The/A}"
echo "Replace suffix: ${sentence/%fox/cat}"
# Split string into array
IFS="," read -ra parts <<< "a,b,c,d,e"
for part in "${parts[@]}"; do
echo "Part: $part"
done
# Repeat string
repeat() {
local str=$1 n=$2
printf "%s" "$str"
for ((i=1; i<n; i++)); do
printf "%s" "$str"
done
}
echo "Repeated: $(repeat "ab" 3)"Bash parameter expansion provides powerful string operations: ${str:offset:length} for substrings, ${str^^}/${str,,} for case conversion, ${str#pattern}/${str##pattern} for prefix removal, ${str%pattern}/${str%%pattern} for suffix removal, and ${str/pattern/replacement} for substitution. IFS with read -ra splits strings into arrays.
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
Report a problem with this exampleOpens a pre-filled issue on GitHub.