簡體   English   中英

Shell腳本:如何將循環輸出保存到數組

[英]Shell script: How to save loop output to array

這是我簡單的shell腳本。 目的是將字符串“ RANDOM948”拆分為數組,以便我可以操縱字符串“ RANDOM948”中的任何字符。

ubuntu@Ubuntu:~$ cat -n longscript.sh 
     1  string="RANDOM948"
     2
     3  c1=${string:0:1}
     4  c2=${string:1:1}
     5  c3=${string:2:1}
     6  c4=${string:3:1}
     7  c5=${string:4:1}
     8  c6=${string:5:1}
     9  c7=${string:6:1}
    10  c8=${string:7:1}
    11  c9=${string:8:1}
    12              
    13  echo $c9 $c4 $c1
ubuntu@Ubuntu:~$ 

ubuntu@Ubuntu:~$ ./longscript.sh 
8 D R
ubuntu@Ubuntu:~$ 

我相信可以通過使用for循環來簡化此過程。 這是我的嘗試。 但是,我不知道如何將循環輸出保存為數組。

ubuntu@Ubuntu:~$ cat -n testscript.sh 
     1  string="RANDOM948"
     2
     3  for i in {1..9}
     4  do
     5   echo c$i=$\{string:`expr $i - 1`:1}
     6  done
     7
     8  # echo $c9 $c4 $c1
ubuntu@Ubuntu:~$ 

ubuntu@Ubuntu:~$ ./testscript.sh 
c1=${string:0:1}
c2=${string:1:1}
c3=${string:2:1}
c4=${string:3:1}
c5=${string:4:1}
c6=${string:5:1}
c7=${string:6:1}
c8=${string:7:1}
c9=${string:8:1}
ubuntu@Ubuntu:~$ 

更新:@sos建議的新代碼

我已經用新行(5&6)更新了此代碼,但是仍然無法正常工作

ubuntu@Ubuntu:~$ cat -n testscript.sh 
     1  string="RANDOM948"
     2
     3  for i in {1..9}
     4  do
     5   typeset -a c
     6   c[${i}]=$\{string:`expr $i - 1`:1}
     7  done
     8
     9  echo TEST OUTPUT $c9 $c4 $c1
ubuntu@Ubuntu:~$ 
ubuntu@Ubuntu:~$ 
ubuntu@Ubuntu:~$ ./testscript.sh 
TEST OUTPUT
ubuntu@Ubuntu:~$ 

更換

    echo c${i}

    typeset -a c       # declare a indexed array
    c[${i}]=...

如果您使用shebang行識別正在運行腳本的內容,那么您將對自己和其他人有所幫助,例如

#!/bin/bash

作為腳本的第一行。 無論如何,以下示例可能會對您有所幫助。

cat ./looptest.sh

注意#! 線....

#!/bin/bash
for i in {0..9}
do
  myArray[$i]="hello_$i"
  echo set the value of myArray[$i]
done
echo the value of myArray[4] is ${myArray[4]}

這是輸出:

set the value of myArray[0]
set the value of myArray[1]
set the value of myArray[2]
set the value of myArray[3]
set the value of myArray[4]
set the value of myArray[5]
set the value of myArray[6]
set the value of myArray[7]
set the value of myArray[8]
set the value of myArray[9]
the value of myArray[4] is hello_4

這就是我得到的

    set -x
    for i in {1..9}
      do
        c[${i}]=${string:`expr $i - 1`:1}
     done
    set +x

    + expr 1 - 1
    + c[1]=R
    + expr 2 - 1
    + c[2]=A
    + expr 3 - 1
    + c[3]=N
    + expr 4 - 1
    + c[4]=D
    + expr 5 - 1
    + c[5]=O
    + expr 6 - 1
    + c[6]=M
    + expr 7 - 1
    + c[7]=9
    + expr 8 - 1
    + c[8]=4
    + expr 9 - 1
    + c[9]=8

注意:從1而不是0開始的數組索引被認為是“不尋常的”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM