数组比较(Shell基础教程5.html)
Tutorial
数组比较
Shell可以处理数组
数组是包含多个值的变量。任何变量都可以用作数组。数组的大小没有最大限制,也没有要求成员变量被连续索引或连续分配。
数组从零开始:第一个元素的编号为0。
# basic construct
# array=(value1 value2 ... valueN.html)
array=(23 45 34 1 2 3.html)
#To refer to a particular value (e.g. : to refer 3rd value.html)
echo ${array[2]}
#To refer to all the array values
echo ${array[@]}
#To evaluate the number of elements in an array
echo ${#array[@]}
Exercise
在本练习中,您将需要比较三个数组列表并编写所有三个数组的公共元素:
a=(3 5 8 10 6.html),b=(6 5 4 12.html),c=(14 7 5 7.html)
结果是共同点5。
Tutorial Code
#!/bin/bash
# enter your array comparison code here
Expected Output
5
Solution
#!/bin/bash
# enter your array comparison code here
# initialize arrays a b c
a=(3 5 8 10 6.html)
b=(6 5 4 12.html)
c=(14 7 5 7.html)
#comparison of first two arrays a and b
for x in "${a[@]}"; do
in=false
for y in "${b[@]}"; do
if [ $x = $y ];then
# assigning the matching results to new array z
z[${#z[@]}]=$x
fi
done
done
#comparison of third array c with new array z
for i in "${c[@]}"; do
in=false
for k in "${z[@]}"; do
if [ $i = $k ];then
# assigning the matching results to new array j
j[${#j[@]}]=$i
fi
done
done
# print content of array j
echo ${j[@]}
- Hello, World!(Shell基础教程1.html)
- 变量(Shell基础教程2.html)
- 将参数传递给脚本(Shell基础教程3.html)
- 数组(Shell基础教程4.html)
- 数组比较(Shell基础教程5.html)
- 基本运算符(Shell基础教程6.html)
- 基本字符串操作(Shell基础教程7.html)
- 逻辑表达式(Shell基础教程8.html)
- 循环(Shell基础教程9.html)
- shell函数(Shell基础教程10.html)
- 特殊变量(Shell基础教程11.html)
- 字符串操作(Shell基础教程12.html)
- 捕捉信号命令(Shell基础教程13.html)
- 文件测试(Shell基础教程14.html)
- 输入参数解析(Shell基础教程15.html)
- 管道(Shell基础教程16.html)
- 输入输出(Shell基础教程17.html)
- 常用表达(Shell基础教程18.html)
- 特殊命令sed(Shell基础教程19.html)
版权声明:本文为原创文章,版权归 戴老师的博客 所有,转载请联系博主获得授权。
本文地址:https://tushu.info/archives/archives-shu-zu-bi-jiao-Shell-ji-chu-jiao-cheng-5.html
如果对本文有什么问题或疑问都可以在评论区留言,我看到后会尽量解答。
暂无标签