G
GuideDevOps
Lesson 8 of 15

String Manipulation

Part of the Shell Scripting (Bash) tutorial series.

String Length

str="Hello, World!"
 
# Length
echo "${#str}"            # 13
 
# Length of first variable content
echo "${#1}"              # Length of first argument

Substring Operations

Extraction

str="abcdefghij"
 
# Get substring
echo "${str:0:3}"         # abc (start 0, length 3)
echo "${str:3:2}"         # de
echo "${str:5}"           # fghij (from position 5)
echo "${str: -3}"         # hij (last 3 characters)

Replacement

str="apple apple apple"
 
# Replace first occurrence
echo "${str/apple/orange}"         # orange apple apple
 
# Replace all occurrences
echo "${str//apple/orange}"        # orange orange orange
 
# Remove pattern
echo "${str//apple}"               # (empty)
 
# Replace at start
echo "${str/#apple/orange}"        # orange apple apple
 
# Replace at end
echo "${str/%apple/orange}"        # apple apple orange

Case Conversion

str="Hello World"
 
# Convert to uppercase
echo "${str^^}"                 # HELLO WORLD
 
# Convert to lowercase
echo "${str,,}"                 # hello world
 
# Using tr command
echo "$str" | tr '[:upper:]' '[:lower:]'  # hello world
echo "$str" | tr '[:lower:]' '[:upper:]'  # HELLO WORLD

Trimming Whitespace

str="  hello world  "
 
# Remove leading/trailing spaces
trimmed="${str%% *}"
trimmed="${trimmed## *}"
 
# Using sed
trimmed=$(echo "$str" | sed 's/^[ \t]*//;s/[ \t]*$//')
 
# Using awk
trimmed=$(echo "$str" | awk '{$1=$1};1')

String Comparison

str1="hello"
str2="world"
 
# Equality
if [ "$str1" = "$str2" ]; then
    echo "Equal"
fi
 
# Lexicographic comparison
if [ "$str1" less "$str2" ]; then
    echo "str1 comes before str2"
fi

Pattern Matching

str="test123.log"
 
# Glob patterns (with [[ ]])
if [[ $str == *.log ]]; then
    echo "Is log file"
fi
 
if [[ $str == test* ]]; then
    echo "Starts with 'test'"
fi
 
# Regular expressions
if [[ $str =~ ^[a-z]+[0-9]+\.[a-z]+$ ]]; then
    echo "Matches pattern"
fi
 
# Extract capture group
if [[ $str =~ ([a-z]+)([0-9]+) ]]; then
    echo "Prefix: ${BASH_REMATCH[1]}"
    echo "Number: ${BASH_REMATCH[2]}"
fi

Splitting Strings

# Split by delimiter
str="one,two,three"
IFS=',' read -ra arr <<< "$str"
 
# Now arr has three elements
echo "${arr[0]}"          # one
echo "${arr[1]}"          # two
echo "${arr[2]}"          # three

Joining Strings

# Join array with delimiter
arr=("one" "two" "three")
result=$(IFS=,; echo "${arr[*]}")
echo "$result"            # one,two,three
 
# Join with space
result="${arr[*]}"
echo "$result"            # one two three

Formatting Strings

# Printf formatting
printf "%s %d\n" "Count" 42     # Count 42
printf "%-10s %10s\n" "Left" "Right"
 
# Padding
num=5
echo "$(printf "%05d" $num)"    # 00005
 
# Printf to variable
formatted=$(printf "Value: %d" 42)
echo "$formatted"

Practical Examples

Extract File Extension

file="archive.tar.gz"
extension="${file##*.}"
echo "Extension: $extension"    # gz

Remove File Path

path="/home/user/documents/file.txt"
filename="${path##*/}"
echo "Filename: $filename"       # file.txt

Parse URL

url="https://user:pass@example.com:8080/path?query=value"
protocol="${url%%://*}"
echo "Protocol: $protocol"       # https