击阵列与阵列元件的每一个字符作为一个字符串的字符 [英] Bash array with each character of that array element as a character of a string

查看:109
本文介绍了击阵列与阵列元件的每一个字符作为一个字符串的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图循环虽然在bash的数组。该数组是AARON目前该数组填充索引0亚伦。我想被表现为如

I am trying to loop though an array in bash. The array is "AARON" currently that array fills index 0 with AARON. I want to be behave as such

ARA [0] = A

ARA [1] = A

ARA [2] = R

ARA [3] = O

ARA [4] = N

ara[0] = A
ara[1] = A
ara[2] = R
ara[3] = O
ara[4] = N

我的剧本目前看起来是这样的。

My script currently looks like this.


#!/bin/bash
declare count
declare -a ara=(AARON)

for name in {A..Z}
do
        count=$((count++))
        for char in ${ara[*]}
        do
                if [[ ${ara[char]} -eq $name ]]
                echo ${ara[char]} # for debugging purposes.
                then
                        sum=$((sum + count))
                fi
        done
done

echo $sum #for debugging purposes.

通常我会通过设置自定义IFS实现这一点,但我不知道我会怎么做,对于字符串的每个字符。

Normally I would achieve this by setting a custom IFS but I don't know how I would do that for each character of string.

推荐答案

您想 = 不是 -eq 的字符串比较。

You want = not -eq for string comparison.

回声$ {ARA [字符]} 行是你的如果测试不是一部分一部分的如果的身体。

Your echo ${ara[char]} line is part of your if test not part of the if body.

计数= $((计数++))分配无法正常工作(它总是设置计数来零)你想((计数++))计数= $((++数))代替。

Your count=$((count++)) assignment doesn't work correctly (it always sets count to zero) you want ((count++)) or count=$((++count)) instead.

您可以使用 $ {strvar:POS:计数} 来得到一个字符串的一部分

You can use ${strvar:pos:count} to get parts of a string.

因此​​,像这样:

#!/bin/bash
declare count
declare -a ara=(AARON)

for name in {A..Z}
do
        ((count++))
        for ((i=0; i<=${#ara[0]}; i++))
        do
                echo ${ara[0]:i:1} # for debugging purposes.
                if [[ ${ara[0]:i:1} = $name ]]
                then
                        sum=$((sum + count))
                fi
        done
done

echo $sum # for debugging purposes.

这篇关于击阵列与阵列元件的每一个字符作为一个字符串的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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