将两位数字作为数组中的单个元素处理 [英] Handling two-digit numbers as a single element in arrays

查看:129
本文介绍了将两位数字作为数组中的单个元素处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个shell脚本以获取以下输出:

I want to write a shell script to get the following output:

$ Enter String: a2b3

aabbb

我在内使用了数组循环,但是它始终无法将字符串中的两位数字值作为单个元素添加到数组中。它总是作为两个独立的元素存储在数组中。

I've used arrays within for loops, but it always fails to append two-digit values from the string, as a single element into the array. It always gets stored as two separate elements in the array.

使用的脚本:

echo "Enter your alphanumeric string: "
read a
n=${#a}

for (( i=0;i<n;i++ ))
do
string[i]=${a:i:1}

if [[ ${string[i]} =~ [a-zA-Z] ]]
then
alpha+=("${string[i]}")
elif [[ ${string[i]} =~ [0-9] ]]
then

if [[ ${string[i+1]} =~ [0-9] ]]
then
num+=${string[i]}${string[i+1]}
elif ! [[ ${string[i+1]} =~ [0-9] ]]
then
num+=("${string[i]}")
fi

fi
done

n=${#num[*]}
for (( i=0;i<n;i++ ))
do
echo num[$i] = ${num[i]}
done

n=${#alpha[*]}
for (( i=0;i<n;i++ ))
do
echo alpha[$i] = ${alpha[i]}
done

n=${#alpha[*]}
for (( i=0;i<n;i++ ))
do
y=${num[i]}
for (( j=0;j<y;j++ ))
do
echo -ne ${alpha[i]}
done
done
echo " "

我得到的输出相同:

$ sh Q1.sh
Enter your alphanumeric string: 
a12b20
num[0] = 1
num[1] = 2
num[2] = 2
num[3] = 0
alpha[0] = a
alpha[1] = b
abb 

我需要将值 12 存储为单个元素 num [ 0] 而不是两个单独的元素, num [0] = 1 num [1] = 2 。与值 20 相同。

I need the value 12 to be stored as a single element num[0] rather than as two individual elements, num[0]=1, num[1]=2. Same with the value 20.

请在这里帮助我....谢谢您。

Please help me out here....thank you in advance.

推荐答案

使用GNU awk:

gawk '{n=split($0,a,/[0-9]+/,s);for(i=1;i<=n;i++){for(j=1;j<=s[i];j++)printf a[i]}}'

例如,

$ echo "A10b2"|gawk '{n=split($0,a,/[0-9]+/,s);for(i=1;i<=n;i++){for(j=1;j<=s[i];j++)printf a[i]}}'
AAAAAAAAAAbb

要了解 gawk 在做什么,请在手册

To understand what gawk is doing, check out split function in the manual.

如果您想坚持击球,这是另一种方法:

If you want to stick to bash, here is another way to do it:

#!/bin/bash
read -p "Enter your alphanumeric string: " a
mapfile -t array < <(echo "$a"|grep -Eo "[a-zA-Z]+[0-9]+")
for x in "${array[@]}"; do
    letters=${x%%[0-9]*}
    digits=${x##*[a-z]}
    printf "%0.s$letters" $(seq 1 $digits)
done
echo

grep 从字符串中获取序列(字母,数字), mapfile 从输出中生成数组。对于 a20b30 ,您将获得一个包含元素 a20 b30 。

grep gets the sequences (letters,digits) from the string and mapfile generates an array from the output. For a20b30, you get an array with elements a20 and b30.

然后对于数组的每个元素,您将获得字母并打印前个数字次。

Then for each element of the array, you get the letters and digits and print the former digits times.

输出示例:

$ bash alpha.sh
Enter your alphanumeric string: x3zx10n2
xxxzxzxzxzxzxzxzxzxzxzxnn

我从printf 的想法a / 17030976>此答案。

I got the printf idea from this answer.

这篇关于将两位数字作为数组中的单个元素处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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