Bash 在参数 $@ 的字符串列表中删除重复项

eva*_*eva 2 bash duplicates

在 bash shell 脚本中,我在 $@ 中收到一个参数列表,它们是: abcdace 根据参数,我需要对案例结构做一些特定的事情。但我只想为 abcde 做

我应该只使用 bash 而不是任何其他语言......我可以使用 awk 例如

for argument in "$@"
do
    case $argument in
a)
.....
Run Code Online (Sandbox Code Playgroud)

尝试了很多东西但没有成功

非常感谢任何帮助

Cha*_*ffy 5

使用关联数组来跟踪您已经看到的参数。请注意,这需要 bash 4.0 或更高版本;Apple 发布的 3.2.x 版本太旧了,因为它只支持数字索引数组(declare -a,但不支持declare -A)。

#!/usr/bin/env bash
case $BASH_VERSION in ''|[0-3].*) echo "ERROR: Bash 4.0+ required" >&2; exit 1;; esac

declare -A seen=( )
declare -a deduped=( )

for arg in "$@"; do                # iterate over our argument list
  [[ ${seen[$arg]} ]] && continue  # already seen this? skip it
  seen[$arg]=1                     # mark as seen going forward...
  deduped+=( "$arg" )              # ...and add to our new/future argv
done

set -- "${deduped[@]}"  # replace "$@" with contents of deduped array
Run Code Online (Sandbox Code Playgroud)

  • 如果您不关心 args 的显示顺序,则可以使用 `set -- "${!seen[@]} 从 `seen` 的键设置 argv,而不是使用单独的数组 `deduped` ”`。 (2认同)