【问题标题】:How to store a continous number in array, bash scripting?如何在数组中存储连续数字,bash脚本?
【发布时间】:2020-03-14 06:53:31
【问题描述】:

在数组中声明和存储一个数字很容易,但问题是用户输入 1234,我想将此数字存储为 $array[0]=1, $array[1]=2, $array[ 2]=3, $array[3]=4 但实际上发生的是 $array[0]=1234, $array[1]=null, $array[2]=null, $array[3]=null .我不知道如何分别存储每个数字

#!/bin/bash
declare -a key
read -p "Enter the encryption key: " numbers
key=($numbers)
echo ${key[0]} 
echo ${key[1]}
echo ${key[2]}
echo ${key[3]}.

实际输出:

输入加密密钥:1234

1234

期望的输出:

输入加密密钥:1234

1

2

3

4

提前谢谢你:)

【问题讨论】:

标签: arrays linux bash shell


【解决方案1】:

也有可能使用

key=(`grep -o . <<< "$numbers"`)

您可以通过使用子字符串表示法${string:initial_index:length_of_substring} 来访问 $numbers 中的不同字母,而无需创建数组:

echo ${numbers:0:1}
echo ${numbers:1:1}
echo ${numbers:2:1}
echo ${numbers:3:1}

【讨论】:

  • @3xploit guy:如果你想使用数组:for ((i=0; i&lt;${#numbers}; i++)); do key[$i]="${numbers:$i:1}"; done
【解决方案2】:

看看你是如何使用read的,所以你已经假设键中没有空格,你可以这样做:

#!/bin/bash
declare str
read -p "Enter the encryption key: " str

# replace each character with that character + space
spaced=$(echo "$str" | sed 's/\(.\)/\1 /g')

# without quotes, array elements will be each of the space-separated strings
numbers=( $spaced )

printf "array element %s\n" "${numbers[@]}"

输出:

Enter the encryption key: hello123
array element h
array element e
array element l
array element l
array element o
array element 1
array element 2
array element 3

【讨论】:

    【解决方案3】:

    你可以试试。

    declare -a key
    read -p "Enter the encryption key: " numbers
    while read -n1 input; do
      key+=("$input")
    done < <(printf '%s' "$numbers")
    
    printf '%s\n' "${key[@]}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2015-08-06
      • 2019-09-01
      • 1970-01-01
      相关资源
      最近更新 更多