删除变量中的特定单词


23

bash脚本中,如何从字符串中删除单词,该单词将存储在变量中。

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

Answers:


30

尝试:

$ printf '%s\n' "${FOO//$WORDTOREMOVE/}"
CATS DOGS FISH

这也工作在ksh93mkshzsh


适当地:

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"

它假定您的单词是用空格分隔的,并且具有删除之前和之后的空格的副作用"$WORDTOREMOVE"


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.