50 lines
1.4 KiB
Bash
Executable File
50 lines
1.4 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
#-------------------------------------------------------------------------------
|
|
# Example 1 for Bash Tips show 18: transforming words in a string
|
|
#
|
|
# This is a contrived and overly complex example to show that replacing
|
|
# selected words in a phrase by different words is a non-trivial exercise!
|
|
#-------------------------------------------------------------------------------
|
|
|
|
#
|
|
# Enable extglob
|
|
#
|
|
shopt -s extglob
|
|
|
|
#
|
|
# What we'll work on and where we'll store the transformed version
|
|
#
|
|
phrase='Now is the time for all good men to come to the aid of the party'
|
|
newphrase=
|
|
|
|
#
|
|
# How to transform words in the phrase and a place to store the keys
|
|
#
|
|
declare -A transform=([good]='bad' [men]='people' [party]='Community')
|
|
declare -a keys
|
|
|
|
#
|
|
# Build an extglob pattern from the keys of the associative array
|
|
#
|
|
keys=( ${!transform[@]} )
|
|
targets="${keys[*]/%/|}" # Each key is followed by a '|'
|
|
targets="${targets%|}" # Strip the last '|'
|
|
targets="${targets// }" # Some spaces got in there too
|
|
pattern="@(${targets})" # Make the pattern at last
|
|
|
|
#
|
|
# Go word by word; if a word matches the pattern replace it by what's in the
|
|
# 'transform' array. Because the pattern has been built from the array keys
|
|
# we'll never have the case where a word doesn't have a transformation.
|
|
#
|
|
for word in $phrase; do
|
|
if [[ $word == $pattern ]]; then
|
|
word=${transform[$word]}
|
|
fi
|
|
newphrase+="$word "
|
|
done
|
|
echo "$newphrase"
|
|
|
|
exit
|