Script Valley
Bash Scripting for Developers
Text Processing and File OperationsLesson 4.2

Bash string manipulation without external tools

parameter expansion, substring extraction, string length, find and replace in variables, prefix and suffix stripping, default values, case conversion, string splitting with IFS

Parameter Expansion: Fast String Ops in Pure Bash

Bash parameter expansion types

Bash's parameter expansion handles most string operations without spawning subprocesses. Prefer it over $(echo ... | sed) for performance.

path="/home/alice/projects/myapp.tar.gz"

# Length
echo ${#path}            # 35

# Substring: ${var:start:length}
echo ${path:6:5}         # alice

# Strip prefix (shortest match)
echo ${path#*/}          # home/alice/projects/myapp.tar.gz

# Strip prefix (longest match)
echo ${path##*/}         # myapp.tar.gz  (basename)

# Strip suffix (shortest match)
echo ${path%.*}          # /home/alice/projects/myapp.tar

# Strip suffix (longest match)
echo ${path%%.*}         # /home/alice/projects/myapp

# Replace first match
echo ${path/projects/repos}  # /home/alice/repos/myapp.tar.gz

# Replace all matches
echo ${path//\//_}       # _home_alice_projects_myapp.tar.gz

Default Values and Validation

name="${1:-world}"        # default if $1 is unset or empty
port="${PORT:=8080}"      # assign default if PORT is unset

# Fail if variable is unset
: "${REQUIRED_VAR:?Error: REQUIRED_VAR must be set}"

Case Conversion (Bash 4+)

str="Hello World"
echo ${str,,}   # hello world  (lowercase)
echo ${str^^}   # HELLO WORLD  (uppercase)

Case conversion requires Bash 4+. macOS ships Bash 3 by default โ€” install Bash via Homebrew for scripts targeting both platforms.

Up next

Parsing CSV and JSON in Bash scripts

Sign in to track progress

Bash string manipulation without external tools โ€” Text Processing and File Operations โ€” Bash Scripting for Developers โ€” Script Valley โ€” Script Valley