String interception and splicing method in Linux

A Linux string truncation is useful. There are eight methods.

Suppose there is variable  var=http://www.linuxidc.com/123.htm 

1# interception, delete the left character, keep the right character. 

echo $ {var # * //

Where var is the variable name, the # sign is the operator, *//  means to delete the first // sign and all the characters on the left from the left

i.e. remove  http://

The result is: www.linuxidc.com/123.htm

 . 

2 ## interception, delete the left character, keep the right character.

echo $ {var ## * /

##*/  means to delete the last (rightmost) / sign and all characters on the left from the left

i.e. remove  http://www.linuxidc.com/         

The result is 123.htm

 

 

3 % sign interception, delete the right character, keep the left character

echo $ {var% / *

%/* means start from the right, delete the first / sign and the characters to the right

The result is: http://www.linuxidc.com

 

 

4 %% interception, delete the characters on the right, keep the characters on the left

 

echo $ {var %% / *

%%/* means start from the right, delete the last (leftmost) / sign and the characters to the right

The result is: http:

 

5 Starting from the first character from the left, and the number of characters

echo $ {var: 0: 5

 

Where 0 indicates the start of the first character on the left, and 5 indicates the total number of characters.

The result is: http:

6 Start with the first few characters from the left and continue to the end.

echo $ {var: 7

The 7 represents the beginning of the 8th character from the left and continues until the end.

The result is: www.linuxidc.com/123.htm

7Starting  from the first character on the right, and the number of characters

echo $ {var: 0-7: 3

Among them, 0-7 means starting from the seventh character from the right, and 3 means the number of characters.

The result is: 123

8 Start with the first few characters from the right and continue to the end.

echo $ {var: 0-7

Indicates from the seventh character from the right to the end.

The result is: 123.htm

Note: (the first character on the left is represented by 0, and the first character on the right is represented by 0-1)

Two splicing method of strings in Linux Shell script


If you want to add a character after the variable, you can use the following method:


$value1=home


$value2=${value1}"="


echo $value2Add


{} to the string variable to be added, and you need to put $ outside .


The result of this output is: home=, which means that 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/

 http://www.linuxidc.com/Linux/2015-03/115198.htm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324979234&siteId=291194637