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)"Report a problem with this exampleOpens a pre-filled issue on GitHub.