Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Several methods of intercepting shell script string

Shulou Source: shulou.com Published: 2022-06-01 01:34:48 09月11日 Update

1. Cut command

The cut command mainly accepts three positioning methods:

First, byte (bytes), with the option-b

Second, the character (characters), with the option-c

Third, fields (domain), with the option-f

Str= "abchyew2635" echo $str | cut-c 6-9

Results:

Yew2

2. # intercept, delete the left character and keep the right character

Var= "hello world" echo ${var#*l} result: lo world

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

That is, delete hel

3. Intercept with # #, delete the left character and retain the right character.

Var= "hello world" echo ${var##*l} result: d

# # * l means to delete the last (rightmost) l and all left characters from the left

That is, delete hello worl

4.% intercept, delete the right character and keep the left character

Var= "hello world" echo ${var%l*} result: hello wor

% l* means to start on the right and delete the first l and the characters on the right

That is, delete d

5.%% intercept, delete the right character and keep the left character

Var= "hello world" echo ${var%%l*} result: he

% l* means to start from the right, delete the last (leftmost) l and the right character

That is, delete llo world

6. Start with the number of characters on the left and the number of characters

Var= "hello world" echo ${var:0:3} result: hel

Where 0 indicates the beginning of the first character on the left, and 3 represents the total number of characters.

7. Start with the first character on the left and end it.

Var= "hello world" echo ${var:2} result: llo world

The 2 of them indicates that the third character on the left begins and ends.

8. Start with the number of characters on the right and the number of characters

Var= "hello world" echo ${var:0-2:3} result: ld

Where 0-2 indicates the start of the second character on the right, and 3 indicates the number of characters.

9. Start with the character on the right and go to the end.

Var= "hello world" echo ${var:0-2} result: ld

Indicates that it starts with the second character on the right and ends.

General Code:

#! / bin/bashvar= "hello world" echo ${var#*l} echo ${var##*l} echo ${var%l*} echo ${var%%l*} echo ${var:0:3} echo ${var:2} echo ${var:0-2:3} echo ${var:0-2} [fbl@www test6_16] $. / string.sh lo worlddhello worhehelllo worldldld

Tags: Character right result number command method three variable byte generalization operator location operation multiple string script Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux OPPO Reno Microsoft MariaDB Apple