Several methods of string interception in shell script
1.# intercept, delete the left character and retain the right character.
Code: echo ${var#*//}
Where var is the variable name, # is the operator, and * / / means to delete the first / / and all characters on the left from the left.
Example:
Results:
2. Intercept the characters on the left and keep the characters on the right
Code: echo ${var##*/}
Where # * / means to delete the last (rightmost) / sign and all characters on the left from the left
Example:
Results:
3.% intercept, delete the right character and keep the left character
Code: echo ${var%/*}
Where% / * means to start on the right and delete the first / sign and the characters on the right
Example:
Results:
4%% intercept, delete the right character and keep the left character
Code: echo ${% / *}
Where% / * means to start from the right and delete the last (leftmost) / and right character
Example:
Results:
5. Start with the number of characters on the left and the number of characters
Code: echo ${var:0:5}
Where 0 indicates the beginning of the first character on the left, and 5 represents the total number of characters
Example:
Results:
6. Start with the character on the left and go to the end
Code: echo ${var:7}
The seven of them starts with the eighth character on the left and ends.
Example:
Results:
7. Start with the number of characters on the right and the number of characters
Code: echo ${var:0-7:3}
Where 0-7 indicates the seventh character from the right, and 3 indicates the number of characters.
Example:
Results:
8. Start with the character on the right and go to the end
Code: echo ${var:0-7}
It starts with the seventh character on the right and ends.
Example:
Results:
The 9.cut command mainly accepts three positioning methods:
(1) Bytes, with option-b
(2) characters, with the option-c
(3) Domain, use the option-f
Example:
From this point of view, there seems to be no difference between-b and-c options, but it is not, because who outputs single-byte characters, so there is no difference between-b and-c. If changed to Chinese, only-c can be used, and-b output is garbled.
The-b and-c we mentioned can only extract information from fixed-format documents, but they are not useful for non-fixed-format information, so "fields" are used.
Example: