Methods for creating sequences and arrays (list, array) in shell

Time:2021-12-29

For Linux array definitions and generation methods, see:Tips for using SEQ to dynamically generate array series from Linux shell。 Here I mainly talk about efficient generation of list strings and array methods.

 

1、 Seq method generation:


[[email protected] shell]$ aNumList=$(seq 100);
[[email protected] 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 gets a string, separated by a space. In Linux, it can be regarded as a list It can be read through the for… In loop.


[[email protected] shell]$ for i in $aNumList;do echo $i;done;
1
2
3
4……

If you need to generate an array, you only need to add $(SEQ 100) and “()”.


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

An array with a length of 100.

 

2、 Generated through internal {begin.. end}

This method is very convenient to generate SEQ. This is done by an internal operator.


[[email protected] ~]$ echo {1..10}
1 2 3 4 5 6 7 8 9 10

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

3、 Performance comparison


[[email protected] ~]$ 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

 

[[email protected] ~]$ 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

As you can see from the above, {begin.. end} is much faster than SEQ call. In the future, it can be considered through internal operators.

Recommended Today

Hive Foundation

1、 Hive basic concepts Hive is a data warehouse tool based on Hadoop. It can map structured data files into a table and provide SQL like query functions. The essence is:Convert HQL into MapReduce program flow chart Architecture Principle Architecture diagram User interface (client):cli (hive shell), jdbc/odbc (Java access hive), webui (browser access hive) Metadata: […]