Note: The subscript of the array in shell starts from 0 by default.
1. Place the string in an array to obtain its length.
Copy codeThe Code is as follows :#! /Bin/bash
Str = "a B -- n d"
Array = ($ str)
Length =$ {# array [@]}
Echo $ length
For (I = 0; I <$ length; I ++ ))
Do
Echo $ {array [$ I]}
Done
Execution result:
[Oracle @ 99bill-as9 array] $ sh length. sh
4
A
-- N
D
2) print the string:
Copy codeThe Code is as follows :#! /Bin/bash
Str = "a B c"
For I in $ str
Do
Echo $ I
Done
Or:
#! /Bin/bash
Str = "a B c"
Array = ($ str)
For (I = 0; I <$ {# array [@]}; I ++ ))
Do
Echo $ {array [$ I]}
Done
Execution result:
A
C
2. When a string is separated by other characters
Copy codeThe Code is as follows :#! /Bin/bash
Str2 = "a # B # c"
A = ($ (echo $ str2 | tr '# ''' | tr-S ''))
Length =$ {# a [@]}
For (I = 0; I <$ length; I ++ ))
Do
Echo $ {a [$ I]}
Done
# Echo $ {a [2]}
Execution result:
A
C
3. Other operations on Arrays
Copy codeThe Code is as follows :#! /Bin/bash
Str = "a B -- n dd"
Array = ($ str)
Length =$ {# array [@]}
# Ouput the first array element outputs the first element of the array.
Echo $ array
# Use subscript way access array access to array elements using the following method
Echo $ {array [1]}
# Output the array to Output this array
Echo $ {array [@]}
# Output in the array subscript for 3 the length of the element Output the length of the element marked as 3 in the array
Echo $ {# array [3]}
# Output in the array subscript 1 to 3 element: Elements marked as 1 to 3 in the Output array
Echo $ {array [@]: 1: 3}
# Output in the array subscript greater than 2 elements Output the element whose subscript is greater than 2
Echo $ {array [@]: 2}
# Output in the array subscript less than 2 elements Output the element whose subscript is less than 2 in the array
Echo $ {array [@]: 2}
Execution result:
A
A B -- n dd
2
B -- n dd
-- N dd
A B
4. Access a string through traversal (separated by spaces by default. When strings are separated by other separators, refer to 2)
Copy codeThe Code is as follows :#! /Bin/bash
Str = "a -- m"
For I in $ str
Do
Echo $ I
Done
Execution result:
A
-- M
5. How to use echo to output a string str = "-n". Because-n is a parameter of echo, the General echo "$ str" method cannot be output.
The solution can be:
Copy codeThe Code is as follows: echo x $ str | sed's/^ x //'
Echo-ne "$ str \ n"
Echo-e "$ str \ n \ c"
Printf "% s \ n" $ str (this can also be done)