Bash

Substring + Find/Replace (parameter expansion)

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Bash's ${var:offset:length} and ${var//pattern/replacement} let you do most string operations without ever spawning sed. Faster, and the syntax is portable across modern shells.
Bash
Raw
s="hello-world-foo-bar"

# Substring (offset, length)
echo "${s:6}"            # world-foo-bar
echo "${s:6:5}"          # world

# Find & replace
echo "${s/-/_}"          # hello_world-foo-bar  (first occurrence)
echo "${s//-/_}"         # hello_world_foo_bar  (all occurrences)
echo "${s/#hello/HI}"    # HI-world-foo-bar      (only if prefix)
echo "${s/%bar/BAZ}"     # hello-world-foo-BAZ   (only if suffix)

# Strip prefix / suffix
file="path/to/config.json"
echo "${file##*/}"       # config.json    (everything after last /)
echo "${file%/*}"        # path/to        (everything before last /)
echo "${file##*.}"       # json           (extension)
echo "${file%.*}"        # path/to/config (sans extension)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.