0

完整的脚本在gitlab上可用

开始时,steam-lr -g menu它会显示使用whiptail. 此菜单中的项目按 排序game id

我的问题:有没有办法订购它们game name

物品是如何产生的:

function build_gamemenu {
  i=0
  for f in ~/.steam/steam/steamapps/*.acf; do
    game_name=$(cat $f | grep \"name\" | sed 's/.*"name"\s*//;s/"//;s/"//')
    game_id=$(cat $f | grep \"appid\" | sed 's/.*"appid"//;s/"//;s/"//;s/^[ \t]*//')
    gamemenu[i]="$game_id"
    gamemenu[i+1]="$game_name"
    ((i+=2))
  done
}
  • 列出的文件夹中的文件名看起来像manifest_GAME_ID.acf (即:manifest_1234.acf)
  • $game_id总是一个数字
  • $game_name可能包含空格和特殊字符

物品如何传递给whiptail:

function menu {
# (...)
game_id=$(whiptail --notags --backtitle "$version" --title "SteamLR" --menu "Select a game:" $w_h $w_w $w_l "${gamemenu[@]}" 2>&1 >/dev/tty)
# (...)
}
  • ${gamemenu[@]}生成正确的计算字符串$game_id "$game_name"。到目前为止,这是我找到的唯一方法。
4

1 回答 1

1

不要对数组使用数字索引;而是使用实际名称。

这样你就可以对你的名字进行带外排序并遍历排序的顺序。

# this is a little more precise than the cat | grep | sed hackery
extract_key() {
  gawk -F'[[:space:]]' -v key="\"$1\"" '
    BEGIN { FPAT = "\"([^\"]+)\""; }
    $1 == key {
      if (substr($2, 1, 1) == "\"") {
        $2 = substr($2, 2, length($2) - 2)
      }
      print $2
      exit(0)
    }
    END { exit(1); }
  '
}

die() { echo "$*" >&2; exit 1; }

build_gamemenu() {
  declare -g -A game_ids=( )  # declare -A makes our array associative
  local f name id             # this way we don't pollute global namespace
  for f in ~/.steam/steam/steamapps/*.acf; do
    name=$(extract_key name <"$f") || die "Could not find name for $f"
    id=$(extract_key appid <"$f") || die "Could not find id for $f"
    game_ids[$name]=$id
  done
}

# note that readarray -d is only available in very new bash releases
# for older releases, instead you can use:
# sorted_names=( ); while IFS= read -r name; do sorted_names+=( "$name" ); done < <(...)
readarray -d '' sorted_names < <(printf '%s\0' "${!game_ids[@]}" | sort -z)
build_gamemenu

然后打印按名称排序的游戏:

for game_name in "${sorted_names[@]}"; do
  game_id=${game_ids[$game_name]}
  echo "$game_name [$game_id]"
done

...或者,生成一个数组传递给whiptail:

whiptail_args=( )
for game_name in "${sorted_names[@]}"; do
  game_id=${game_ids[$game_name]}
  whiptail_args+=( "$game_id" "$game_name" )
done
于 2018-07-22T17:11:56.610 回答