Bash – Remove specific word in variable

bashshell-scriptvariable

In a bash script, how can I remove a word from a string, the word would be stored in a variable.

FOO="CATS DOGS FISH MICE"
WORDTOREMOVE="MICE"

Best Answer

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".

Related Question