#!/bin/bash
# patt-matching.sh
# Pattern matching using the # ## % %% parameter substitution operators.
var1=abcd12345abc6789
pattern1=a*c # * (wild card) matches everything between a - c.
echo
echo "var1 = $var1" # abcd12345abc6789
echo "var1 = ${var1}" # abcd12345abc6789
# (alternate form)
echo "Number of characters in ${var1} = ${#var1}"
echo
echo "pattern1 = $pattern1" # a*c (everything between 'a' and 'c')
echo "--------------"
echo '${var1#$pattern1} =' "${var1#$pattern1}" # d12345abc6789
# Shortest possible match, strips out first 3 characters abcd12345abc6789
# ^^^^^ |-|
echo '${var1##$pattern1} =' "${var1##$pattern1}" # 6789
# Longest possible match, strips out first 12 characters abcd12345abc6789
# ^^^^^ |----------|
echo; echo; echo
pattern2=b*9 # everything between 'b' and '9'
echo "var1 = $var1" # Still abcd12345abc6789
echo
echo "pattern2 = $pattern2"
echo "--------------"
echo '${var1%pattern2} =' "${var1%$pattern2}" # abcd12345a
# Shortest possible match, strips out last 6 characters abcd12345abc6789
# ^^^^ |----|
echo '${var1%%pattern2} =' "${var1%%$pattern2}" # a
# Longest possible match, strips out last 12 characters abcd12345abc6789
# ^^^^ |-------------|
# Remember, # and ## work from the left end (beginning) of string,
# % and %% work from the right end.
echo
exit 0
AskApache Web Development