庆典 - 确定一个变量的子字符串时,关联子到另一个变量是已知的 [英] bash - determine a substring in one variable when an associated substring is known in another variable

查看:111
本文介绍了庆典 - 确定一个变量的子字符串时,关联子到另一个变量是已知的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个字符串,一人空格分隔一串钥匙,另一个充当每个第一按键的联想空间分隔的值:

Assuming I had two strings, one acts a string of space delimited keys, and another acts as the associative space-delimited values for each of the keys in the first:

KEYS="key_1 key_2 key_3"
VALS="value1 aDifferentValue_2 theFinalValue"

因此​​,在这种情况下, key_1 $键的关联值值1 key_2 不得不 aDifferentValue_2 的关联值,依此类推。说有问题的关键是 key_2 ,存储在变量 $ FIELD ,究竟是用最简单的方式SED和/或AWK找出基于关闭其字位置,该值必须是 aDifferentValue_2 ?有没有一种方法来创建一个使用 $键子的关联数组作为键和 $ VALS 作为值?

So in this case, key_1 in $KEYS has an associated value of value1, key_2 had an associated value of aDifferentValue_2, and so on. Say the key in question was key_2, stored in variable $FIELD, what is the easiest way using sed and/or awk to find out that based off its word position, the value must be aDifferentValue_2? Is there a way to create an associative array using the substrings of $KEYS as the keys and $VALS as the values?

推荐答案

由于这是标记庆典,你可以有实际关联数组(bash的V4):

Since this is tagged bash, you can have actual associative arrays (bash v4):

KEYS="key_1 key_2 key_3"
VALS="value1 aDifferentValue_2 theFinalValue"
keys=( $KEYS )
vals=( $VALS )
declare -A map
for (( i=0; i<${#keys[@]}; i++ )); do
  map["${keys[$i]}"]="${vals[$i]}"
done
for idx in "${!map[@]}"; do
  echo "$idx -> ${map[$idx]}"
done

输出

key_1 -> value1
key_2 -> aDifferentValue_2
key_3 -> theFinalValue

如果你没有bash的V4,你仍然可以使用丘壑索引的数组和:

If you don't have bash v4, you can still use the keys and vals indexed arrays and:

get_key_idx() {
  for (( i=0; i<${#keys[@]}; i++ )); do 
    if [[ "$key" = "${keys[$i]}" ]]; then
      echo $i
      return 0
    fi
  done
  return 1
}

key="key_2"
if idx=$(get_key_idx $key); then
  echo "$key -> ${vals[$idx]}"
else
  echo "no mapping for $key"
fi

这篇关于庆典 - 确定一个变量的子字符串时,关联子到另一个变量是已知的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆