Skip to content
Bash

String Operations

Bash string processing.

By EZ4Code Team
bashstring

Code

#!/bin/bash

str="Hello, World!"

# String length
echo ${#str}  # 13

# Substring
echo ${str:0:5}    # Hello
echo ${str:7}      # World!
echo ${str: -6}    # World! (from end)

# Find and replace
echo ${str/World/Bash}   # Hello, Bash! (replace first)
echo ${str//o/0}         # Hell0, W0rld! (replace all)
echo ${str/#Hello/Hi}    # Hi, World! (replace prefix)
echo ${str/%!/.}         # Hello, World. (replace suffix)

# Delete substring
file="archive.tar.gz"
echo ${file%.gz}         # archive.tar (remove suffix)
echo ${file%%.*}         # archive (remove longest suffix)
echo ${file#archive.}    # tar.gz (remove prefix)
echo ${file##*.}         # gz (remove longest prefix)

# Case conversion
echo ${str^^}  # HELLO, WORLD! (uppercase)
echo ${str,,}  # hello, world! (lowercase)
echo ${str^}   # Hello, World! (capitalize first letter)

# String split
IFS=',' read -ra parts <<< "a,b,c"
for part in "${parts[@]}"; do
    echo "$part"
done

# String contains
if [[ $str == *"World"* ]]; then
    echo "Contains World"
fi

# Regex match
if [[ $str =~ ^Hello ]]; then
    echo "Starts with Hello"
fi

# Extract match group
if [[ $str =~ ([A-Z][a-z]+), ([A-Z][a-z]+) ]]; then
    echo ${BASH_REMATCH[1]}  # Hello
    echo ${BASH_REMATCH[2]}  # World
fi

# Trim whitespace
str="  hello  "
echo "${str// /}"  # hello (delete all spaces)
echo "$(echo $str)"  # hello (trim)

Explanation

Bash string operations include length, substring, replace, delete, case conversion, and regex matching, using ${var} syntax.

More Bash Snippets