bash 迭代并替换数组中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45207167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:18:28  来源:igfitidea点击:

Iterate over and replace element in array

bash

提问by nhershy

I am trying to replace the word "Apples" with "Cantaloupe" in my 'copy' array. What I am doing now is not throwing errors, but no change occurs in the copy array.

我试图在我的“副本”数组中用“哈密瓜”替换“苹果”这个词。我现在所做的不是抛出错误,而是复制数组中没有发生任何变化。

#!/bin/bash

fruits=("Oranges" "Apples" "Bananas" "Grapes")
echo "Original list:"
echo "${fruits[@]}"

copy=("${fruits[@]}")

for i in ${copy[@]}
do
        if [[ copy[$i] == "Apples" ]]; then
                copy[$i]="Canteloupe"
        fi
done

echo "Copied list:"
echo "${copy[@]}"

My output:

我的输出:

Original list:
Oranges Apples Bananas Grapes
Copied list:
Oranges Apples Bananas Grapes

采纳答案by Inian

In your original approach you are looping over the keysin the array using which you would not be able to get the index of that element to replace.

在您的原始方法中,您正在循环使用数组中的,您将无法获取要替换的元素的索引。

You need to change to modify the logic to loop over indicesof the array as

您需要更改以修改逻辑以循环数组的索引作为

for i in "${!copy[@]}"; do
    if [[ ${copy[$i]} == "Apples" ]]; then
        copy[$i]="Canteloupe"
    fi
done

should solve your problem.

应该可以解决您的问题。

The construct for i in "${!copy[@]}"; dois for looping with indices of the array starting from 0to size of the array which lets you to replace the element in the index where you find the required string.

该构造for i in "${!copy[@]}"; do用于循环使用数组的索引,从数组的0大小开始,这使您可以替换索引中找到所需字符串的元素。



Expanding the answer to point out the difference when using either of array iteration ways.

扩展答案以指出使用任何一种数组迭代方式时的差异。

Looping over indices

循环索引

for i in "${!copy[@]}"; do 
  printf "%s\t%s\n" "$i" "${copy[$i]}"
done

prints

印刷

0       Oranges
1       Apples
2       Bananas
3       Grapes

and over keys

和过键

for i in "${copy[@]}"; do 
  printf "%s\n" "$i"
done

produces,

产生,

Oranges
Apples
Bananas
Grapes

回答by Sergey Shevchenko

The solution explained in the accepted answer to this similar questionmight be preferable:

在这个类似问题的公认答案中解释的解决方案可能更可取:

array=("${array[@]/Apples/Canteloupe}")

array=("${array[@]/Apples/Canteloupe}")

This depends on your general attitude towards Bash trickery. In technical terms, there are no downsides to manually iterating over the elements.

这取决于您对 Bash 诡计的总体态度。从技术角度来说,手动迭代元素没有任何缺点。