广告
返回顶部
首页 > 资讯 > 服务器 >Shell中创建序列和数组(list、array)的方法
  • 675
分享到

Shell中创建序列和数组(list、array)的方法

数组序列方法 2022-06-04 21:06:07 675人浏览 泡泡鱼
摘要

关于linux数组定义,以及生成方法,请看:linux shell 动态生成 数组系列 seq使用技巧 。这里我主要说的是高效生成list 字符串,还有数组方法。 一、seq方法生成: [chen

关于linux数组定义,以及生成方法,请看:linux shell 动态生成 数组系列 seq使用技巧 。这里我主要说的是高效生成list 字符串,还有数组方法。

一、seq方法生成:


[chengmo@Centos5 shell]$ aNumList=$(seq 100);
[chengmo@centos5 shell]$ echo $aNumList
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

aNumList得到是字符串,不同之处以:空格分隔开。在linux里面,可以把它看作是list. 可以通过for…in 循环读取。


[chengmo@centos5 shell]$ for i in $aNumList;do echo $i;done;
1
2
3
4……

如果需要生成array只需要将$(seq 100) 再加个”()”即可。


[chengmo@centos5 ~]$ aNumList=($(seq 100));
[chengmo@centos5 ~]$ echo $aNumList
1
[chengmo@centos5 ~]$ echo ${#aNumList[@]}
100

长度是100的数组。

二、通过内部{begin..end}生成

这种方法生成seq非常方便。通过内部运算符完成。


[chengmo@centos5 ~]$ echo {1..10}
1 2 3 4 5 6 7 8 9 10

[chengmo@centos5 ~]$ for a in {1..10};do echo $a;done; 
1
2
3
4
5
6
7
8
9
10

三、性能比较


[chengmo@centos5 ~]$ time echo {1..100}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

real  0m0.000s
user  0m0.001s
sys   0m0.000s

 

[chengmo@centos5 ~]$ time echo $(seq 100)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

real  0m0.003s
user  0m0.002s
sys   0m0.001s

从上面可以看到,{begin..end}速度比seq调用快了不少了。 以后调用时候可以考虑通过内部操作符完成。

--结束END--

本文标题: Shell中创建序列和数组(list、array)的方法

本文链接: https://www.lsjlt.com/news/18495.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作