Summary of 8 String Interception Methods in Shell Script

 

Summary of 8 String Interception Methods in Shell Script

Get the path (directory) where the current shell script is located, supports soft links.

DIR=`S=\`readlink "$0"\`; [ -z "$S" ] && S=$0; dirname $S`
$0: Get the name of the current script
$#: the number of arguments passed to the script
$$: Process ID of the shell script
$1, $2, $3...: Script parameters

String truncation for Linux is useful. There are eight methods.

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

1. Intercept the # sign, delete the characters on the left, and keep the characters on the right.

 

copy code code show as below:

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,
that is, delete http://
and the result is: www.aaa.com/123.htm

2. The ## sign is intercepted, the characters on the left are deleted, and the characters on the right are reserved.

 

copy code code show as below:

echo $ {var ## * /

 

##*/ means to delete the last (rightmost) / sign from the left and all the characters on the left to
delete http://www.aaa.com/

The result is 123.htm

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

 

copy code code show as below:

echo $ {var% / *

 

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

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

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

 

copy code code show as below:

echo $ {var %% / *

 

%%/* means start from the right, delete the last (leftmost) / sign and the characters on the right. The
result is: http:

5. The first character from the left, and the number of characters

 

copy code code show as below:

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. 从左边第几个字符开始,一直到结束。

 

复制代码代码如下:

echo ${var:7}

 

其中的 7 表示左边第8个字符开始,一直到结束。
结果是 :www.aaa.com/123.htm

7. 从右边第几个字符开始,及字符的个数

 

复制代码代码如下:

echo ${var:0-7:3}

 

其中的 0-7 表示右边算起第七个字符开始,3 表示字符的个数。
结果是:123

8. 从右边第几个字符开始,一直到结束。

 

复制代码代码如下:

echo ${var:0-7}

 

表示从右边第七个字符开始,一直到结束。
结果是:123.htm

注:(左边的第一个字符是用 0 表示,右边的第一个字符用 0-1 表示)

Guess you like

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