Linux逐行数组赋值实战攻略 (linux逐行 数组 赋值)

在Linux的bash shell脚本里,数组是一个非常实用的数据结构。在实际的工作中,我们经常需要使用数组来存储一些数据,进行计算、比较、排序等操作。有时候,我们需要将数组进行逐行赋值,这种操作需要掌握一些技巧。本文将介绍Linux逐行数组赋值的实战攻略,希望对你的工作有所帮助。

1. 定义数组

在bash脚本中定义数组很简单,只需要使用括号将数组中的元素括起来,中间用空格分隔。例如:

“`

#!/bin/bash

fruits=(“apple” “banana” “orange” “grape” “peach”)

“`

2. 逐行读取文件

在处理一些数据时,我们常常需要从文件中逐行读取数据,例如:

“`

#!/bin/bash

while read line

do

echo $line

done

“`

3. 逐行数组赋值

假如我们有一个文件input.txt,里面有若干行文字,我们想将它们存储到一个数组中。我们可以先定义一个空数组,然后逐行读取文件,将每行文字作为数组元素存储起来。例如:

“`

#!/bin/bash

fruits=()

while read line

do

fruits+=($line)

done

echo ${fruits[@]}

“`

注意,数组的+=操作不会覆盖原有的数组,它会在原有数组的末尾添加新的元素。如果我们想覆盖原有的数组,可以使用如下的方式:

“`

#!/bin/bash

fruits=()

while read line

do

fruits=(“${fruits[@]}” $line)

done

echo ${fruits[@]}

“`

4. 逐行读取数组

有时候,我们需要逐行读取已经存在的数组,并对每行数据进行处理。例如:

“`

#!/bin/bash

fruits=(“apple” “banana” “orange” “grape” “peach”)

for fruit in “${fruits[@]}”

do

echo $fruit

done

“`

这里的关键是”${fruits[@]}”,它可以将整个数组展开成一个字符串列表。在for循环中,我们使用fruit来逐个读取列表中的字符串,就可以实现逐行读取数组的目的了。

5. 逐行修改数组

有时候,我们需要对一个数组逐行进行修改。例如,给数组fruits中的每个元素加上一个前缀”good”,可以使用如下的方法:

“`

#!/bin/bash

fruits=(“apple” “banana” “orange” “grape” “peach”)

for i in “${!fruits[@]}”

do

fruits[$i]=”good${fruits[$i]}”

done

echo ${fruits[@]}

“`

这里使用了”${!fruits[@]}”,它可以展开成一个字符串列表,其中每个字符串是数组fruits中的索引。在for循环中,我们使用i来逐个读取列表中的索引,通过”${fruits[$i]}”来读取数组中的元素,然后对元素进行修改。

6. 实例

下面是一个完整的例子,它将逐行读取文件input.txt,将每行文字加上前缀”good”,然后逐行存储到数组fruits中:

“`

#!/bin/bash

fruits=()

while read line

do

line=”good $line”

fruits=(“${fruits[@]}” “$line”)

done

for fruit in “${fruits[@]}”

do

echo $fruit

done

“`

在这个例子中,我们使用了多种技巧,包括数组元素逐行添加、逐行遍历数组、逐行修改数组等操作。这些技巧在实际的工作中都非常有用,能够帮助我们快速高效地处理数据。

Linux逐行数组赋值是一个重要的技巧,在实际的工作中非常有用。本文介绍了如何逐行读取文件、逐行数组赋值、逐行遍历数组和逐行修改数组等操作,希望能够帮助大家更加熟练地使用Linux的bash脚本。

相关问题拓展阅读:

linux 数组问题求解

比较正确的数组索引用法如下:

#!/bin/bash

declare ass_array

index1=0

index2=1

ass_array=(=apple =orange)

echo “apple is ${ass_array}”

echo ${ass_array}

echo ${ass_array}

echo ${#ass_array}

echo index0 is

echo ${ass_array}

echo index1 is

echo ${ass_array}

输出结果如下

################################################################

你错的原因如下:

1.不太清楚如何使用索引给数组元素赋值。

2.没有给index1,index2赋值,导致它们为空,它们在被当销唯做数字使用时,亏碰培值吵搏为0

ass_array=( =orange)

等效于

ass_array=(= =orange)

即,

之一个元素ass_array 内容首先被赋值为字符串:

马上,ass_array的值又被赋值为字符串:orange

所以,

echo “apple is ${ass_array}”

等效于

echo “apple is ${ass_array}”

你得到结果:

apple is orange

###### 你的第二次尝试 ##############

由于没有给index1,index2赋值,导致它们为空,它们在被当做数字使用时,值为0

ass_array=(=apple =orange)

等效于:

ass_array=(=apple =orange)

ass_array的值,先被赋值为 apple,又紧接着被赋值为 orange

所以

echo “apple is ${ass_array}”

等效于

echo “apple is ${ass_array}”

你得到结果:

apple is orange

关于linux逐行 数组 赋值的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。


数据运维技术 » Linux逐行数组赋值实战攻略 (linux逐行 数组 赋值)