【问题标题】:why my array always stores the data just first index?为什么我的数组总是只存储第一个索引的数据?
【发布时间】:2019-09-29 21:25:44
【问题描述】:
while read -r line
  do
   local format=()
   for c in "$line"
     do
      format+=("$line")
     done
  for ((x=0; x< ${#format[@]} ;x++)) # this part just iterate 0 
                                     ##index because whole string 
                                      #stores only 0 index
    do
      echo "${format[$x]} $x "
    done
done <$1

此代码仅将数据存储在 0 索引中,例如我有一个字符串是“你好,这是我的世界”,这整个字符串存储在 0 索引中,但我想将每个单词分别存储在字符串中。如何我可以这样做吗?

这就是我想要的 ==[hello,this,is,my,world]

【问题讨论】:

标签: bash shell command-line terminal


【解决方案1】:

for c in "$line" -- 因为你引用了“$line”,所以你正在迭代一个项目。

要将字符串的单词存储到数组中,请使用此处字符串中的read -a

read -ra format <<<"$line"

【讨论】:

  • 但是如果我在 for 循环中写 echo "$line" 这将单独打印不是吗。@glenn jackman
  • print separate doesn't it - 不,它将打印带有空格的单个参数。这是视觉上/打印后无法区分的。尝试printf "%s\n" "$line" 并与printf "%s\n" $line 进行比较。
猜你喜欢
  • 2018-07-12
  • 1970-01-01
  • 2020-06-05
  • 2019-10-14
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2015-10-27
  • 2021-04-20
相关资源
最近更新 更多