【问题标题】:Search array for string and return position in unix在unix中搜索字符串并返回位置
【发布时间】:2014-03-09 07:15:05
【问题描述】:

我有一个二维数组,由第一维中的字母和第二维中的数字组成。例如

a,1
b,3
c,9
d,8

我想做的是在数组中搜索一个字符并返回它对应的数字。例如,如果 $var='c' 则返回值为 9。

由于不熟悉 Unix 数组,我想知道是否有人知道如何简单地做到这一点?

谢谢:)

【问题讨论】:

  • 你的例子和你写的相矛盾——array made up of numbers in the first dimension and letters in the second dimension
  • 此外,如果您对某事不熟悉,不尝试就提出问题不太可能有帮助。
  • 字母为keys的数组称为关联数组。你有bash 版本 4 或更高版本吗?如果没有,那么它无论如何都不适合你。
  • 你有一个实际的bash 数组,还是只是一个文件或输出流,每行都有一对letter,number
  • @Devnull。对不起,有一个小错误,但我希望你明白我的意思。来自 C# 背景,我认为这将是一件容易的事情,但似乎找不到合适的命令

标签: arrays bash unix search


【解决方案1】:

这是我想出来的

arr1=(a b c d)
arr2=(1 3 9 8)

for ((index=0; index<${#arr1[@]}; index++)); do 
if [ "${arr1[$index]}" = "$myCharacter" ]; then
    echo $arr2[$index]
    return
fi
done
echo 'Character not found'

不确定是否有更短的方法可以做到这一点,但工作正常......

【讨论】:

    【解决方案2】:

    假设您有一个名为 array.txt 的文件,其输入与您在问题中显示的一样,

    $ var=c
    $ awk -v key="$var" -F, '$1 ~ key {print $2; found=1} END { if (! found) { print "Key "key" not found";}}' array.txt
    9
    $ var=z
    $ awk -v key="$var" -F, '$1 ~ key {print $2; found=1} END { if (! found) { print "Key "key" not found";}}' array.txt
    Key z not found
    

    【讨论】:

      【解决方案3】:

      您可以使用 bash 准备一个关联数组并使用字符查找值:

       declare -A ARR
       ARR=( [a]=1 [b]=3 [c]=9 [d]=8 )
       echo ${ARR[c]}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-19
        • 2011-01-18
        • 2012-07-21
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        • 2016-02-02
        • 1970-01-01
        相关资源
        最近更新 更多