Remove specific word in variable
Try:
$ printf '%s\n' "${FOO//$WORDTOREMOVE/}"
CATS DOGS FISH
This also work in ksh93
, mksh
, zsh
.
POSIXLY:
FOO="CATS DOGS FISH MICE"
WORDTOREMOVE="MICE"
remove_word() (
set -f
IFS=' '
s=$1
w=$2
set -- $1
for arg do
shift
[ "$arg" = "$w" ] && continue
set -- "$@" "$arg"
done
printf '%s\n' "$*"
)
remove_word "$FOO" "$WORDTOREMOVE"
It assumes your words are space delimited and has side effect that remove spaces before and after "$WORDTOREMOVE"
.
Using bash
substring replacement:
FOO=${FOO//$WORDTOREMOVE/}
The //
replaces all occurences of the substring ($WORDTOREMOVE
) with the content between /
and }
. In this case nothing.
For information on this and other ways to work with strings in bash, see the section 10.1. Manipulating Strings of the Advanced Bash-Scripting Guide.
echo $FOO | sed s/"$WORDTOREMOVE"//