Variable interception in linux shell script

Linux string interception command
reprinted https://www.cnblogs.com/dalianpai/p/12702237.html

When I wrote the shell again today, I felt that the string interception was not particularly smooth. Finally, I used the cutting string to get it.

Define variables

[root@iZ1la3d1xbmukrZ ~]# net=https://www.cnblogs.com/dalianpai/
[root@iZ1la3d1xbmukrZ ~]#

1. The # sign is intercepted, the left character is deleted, and the right character is retained.

[root@iZ1la3d1xbmukrZ ~]# echo ${net#*//}
www.cnblogs.com/dalianpai/
[root@iZ1la3d1xbmukrZ ~]#

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

2. ## is intercepted, the left character is deleted, and the right character is retained.

[root@iZ1la3d1xbmukrZ ~]# echo ${net##*/}

[root@iZ1la3d1xbmukrZ ~]#

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

3. The% sign is intercepted, the right character is deleted, and the left character is retained

[root@iZ1la3d1xbmukrZ ~]# echo ${net%/*}
https://www.cnblogs.com/dalianpai
[root@iZ1la3d1xbmukrZ ~]#

%/* means starting from the right, delete the first / and the characters on the right

4. The %% sign is intercepted, the right character is deleted, and the left character is retained

[root@iZ1la3d1xbmukrZ ~]# echo ${net%%/*}
https:
[root@iZ1la3d1xbmukrZ ~]#

%%/* means starting from the right, deleting the last (leftmost) / sign and the characters on the right

5. Starting from the first few characters from the left, and the number of characters

[root@iZ1la3d1xbmukrZ ~]# string="runoob is a great site"
[root@iZ1la3d1xbmukrZ ~]# echo ${string:0:${#string}-4}
runoob is a great

The 0 means the first character from the left starts

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

[root@iZ1la3d1xbmukrZ ~]# echo ${net:7}
/www.cnblogs.com/dalianpai/
[root@iZ1la3d1xbmukrZ ~]#

The 7 represents the beginning of the eighth character from the left and continues to the end.

7. Starting from the first few characters from the right, and the number of characters

[root@iZ1la3d1xbmukrZ ~]# echo ${net:0-7:3}
ian
[root@iZ1la3d1xbmukrZ ~]#

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

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

[root@iZ1la3d1xbmukrZ ~]# echo ${net:0-7}
ianpai/
[root@iZ1la3d1xbmukrZ ~]#

Indicates starting from the seventh character from the right and continuing to the end.

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

Guess you like

Origin blog.csdn.net/weixin_44578029/article/details/111276393