Linux bash string processing encyclopedia _linux Shell

Source: Internet
Author: User

Gets the length of the string

Copy Code code as follows:

Code:
%x= "ABCD"
#方法一
%expr length $x
4
# method Two
%echo ${#x}
4
# method Three
%expr "$x": ". *"
4
# Help for expr
# String:regexp anchored pattern Match of REGEXP in STRING

Find substring

Copy Code code as follows:

Code:
%expr index $x "B"
2
%expr index $x "a"
1
%expr index $x "B"
2
%expr index $x "C"
3
%EXPR index $x "D"
4

Get substring

Copy Code code as follows:

Code:
# method One
# expr <string> startpos length
%expr substr "$x" 1 3
Abc
%expr substr "$x" 1 5
Abcd
%expr substr "$x" 2 5
Bcd
# method Two
# ${x:pos:lenght}
%echo ${x:1}
Bcd
%echo ${x:2}
Cd
%echo ${x:0}
Abcd
%echo ${x:0:2}
Ab
%pos=1
%len=2
%echo ${x: $pos: $len}
Bc


Matching Regular expressions

Copy Code code as follows:

Code:
# Print Match length
%expr match $x "."
1
%expr match $x "ABC"
3
%expr match $x "BC"
0

Qiatouquwei of strings

Copy Code code as follows:

Code:
%x=aabbaarealwwvvww
%echo "${x%w*w}"
Aabbaarealwwvv
%echo "${x%%w*w}"
Aabbaareal
%echo "${x# #a *a}"
Lwwvvww
%echo "${x#a*a}"
Bbaarealwwvvww

Where, # means pinch head, because on the keyboard # on the left of $.
Where% represents% because the keyboard is on the right side of the $.
A single representation minimum match, with two representing the maximum match.
In other words, when matching a variety of scenarios, choose the maximum length of the match or the minimum length.

Substitution of strings

Copy Code code as follows:

Code:
%x=abcdabcd
%echo ${x/a/b} # replaces only one
Bbcdabcd
%echo ${x//a/b} # Replaces all
Bbcdbbcd

Can't use RegExp, can only use *? The file extension method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.