Linux shell string truncation and splicing, linuxshell
Linux string truncation is very useful. There are eight methods.
Assume there are variablesVar = http://www.hao.com/123.htm
1 # intercept, delete the characters on the left, and retain the characters on the right.
Echo $ {var #*//}
Where var is the variable name and # is the operator,*//Indicates that the first // number and all characters on the left are deleted from the left.
DeleteHttp ://
The result is:Www.hao.com/123.htm
.
2 ## intercept, delete the characters on the left, and retain the characters on the right.
Echo $ {var ##*/}
##*/Indicates that the last (rightmost) character and all characters on the left are deleted from the left.
DeleteHttp://www.hao.com/
The result is 123.htm.
Intercept No. 3%, delete the right character, retain the Left character
Echo $ {var % /*}
%/* Indicates that the first/number and the character on the right are deleted from the right.
Result: http://www.hao.com
Truncated at 4% %, delete the right character, retain the Left character
Echo $ {var % /*}
%/* Indicates that the last (leftmost) character and the character on the right are deleted from the right.
The result is: http:
5. Start from the number of characters on the left and the number of characters.
Echo $ {var: 0: 5}
0 indicates the first character on the left, and 5 indicates the total number of characters.
The result is: http:
6 starts from the number of characters on the left until the end.
Echo $ {var: 7}
7 indicates the start of 8th characters on the left until the end.
The result is:Www.hao.com/123.htm
7Starting from the number of characters on the right and the number of characters
Echo $ {var: 0-7:3}
0-7 indicates the 7th character on the right and 3 indicates the number of characters.
Result: 123
8 starts from the number of characters on the right until the end.
Echo $ {var: 0-7}
Starts from the seventh character on the right and ends.
The result is 123.htm.
.
.
Note: (the first character on the left is 0, and the first character on the right is 0-1)
2. How to concatenate strings in Linux Shell scripts
To add a character to the variable, use the following method:
$ Value1 = home
$ Value2 =$ {value1} "="
Echo $ value2
Add {} to the string variable to be added, and put $ outside.
The output result is: home =, that is, the connection is successful.
Another example:
[Root @ localhost sh] # var1 =/etc/
[Root @ localhost sh] # var2 = yum. repos. d/
[Root @ localhost sh] # var3 =$ {var1 }$ {var2}
[Root @ localhost sh] # echo $ var3
/Etc/yum. repos. d/