Bash String Manipulation - Substring, Replace, Trim, Case

Learn bash parameter expansion for string operations including substring extraction, pattern replacement, prefix/suffix removal, default values, and case conversion.

String Manipulation

Detailed Explanation

String Manipulation in Bash

Bash provides powerful string manipulation through parameter expansion. These operations run without spawning external processes, making them faster than using sed or awk for simple transformations.

String Length

str="Hello, World!"
echo ${#str}    # 13

Substring Extraction

str="Hello, World!"
echo ${str:7}      # World!       (from offset to end)
echo ${str:0:5}    # Hello        (offset and length)
echo ${str: -6}    # orld!        (from end, note the space)

Pattern Replacement

path="/home/user/documents/report.pdf"

# Replace first occurrence
echo ${path/user/admin}       # /home/admin/documents/report.pdf

# Replace all occurrences
echo ${path//\//|}            # |home|user|documents|report.pdf

Prefix and Suffix Removal

file="archive.tar.gz"

# Remove shortest prefix match
echo ${file#*.}       # tar.gz

# Remove longest prefix match
echo ${file##*.}      # gz (just the extension)

# Remove shortest suffix match
echo ${file%.*}       # archive.tar

# Remove longest suffix match
echo ${file%%.*}      # archive (base name)

Default Values

# Use default if unset or empty
echo ${PORT:-3000}

# Assign default if unset or empty
: ${PORT:=3000}

# Use alternative if set
echo ${DEBUG:+--verbose}

# Error if unset
echo ${DB_HOST:?"DB_HOST is required"}

Case Conversion (Bash 4+)

text="Hello World"
echo ${text^^}    # HELLO WORLD (all uppercase)
echo ${text,,}    # hello world (all lowercase)
echo ${text^}     # Hello World (capitalize first letter)

Practical Examples

# Extract filename from path
filepath="/var/log/app/server.log"
filename=${filepath##*/}          # server.log
directory=${filepath%/*}          # /var/log/app

# Change file extension
for file in *.jpeg; do
  mv "$file" "${file%.jpeg}.jpg"
done

# Build URL from parts
PROTOCOL=${PROTOCOL:-https}
HOST=${HOST:?"HOST is required"}
PORT=${PORT:+:$PORT}
URL="${PROTOCOL}://${HOST}${PORT}"

Use Case

String manipulation is essential in bash scripts for processing filenames (extracting extensions, base names, directory paths), building dynamic strings (URLs, file paths, log messages), implementing configuration with default values, and transforming data without relying on external commands like sed or awk.

Try It — Bash Cheat Sheet

Open full tool