Linux bash string processing

Source: Internet
Author: User

Returns the length of a string.

Copy codeThe Code is as follows:
% X = "abcd"
# Method 1
% Expr length $ x
4
# Method 2
% Echo $ {# x}
4
# Method 3
% Expr "$ x ":".*"
4
# Expr help
# STRING: REGEXP anchored pattern match of REGEXP in STRING

Search for substrings

Copy codeThe Code is as follows:
% Expr index $ x "B"
2
% Expr index $ x ""
1
% Expr index $ x "B"
2
% Expr index $ x "c"
3
% Expr index $ x "d"
4

Obtain the substring

Copy codeThe Code is as follows:
# Method 1
# Expr <string> startpos length
% Expr substr "$ x" 1 3
Abc
% Expr substr "$ x" 1 5
Abcd
% Expr substr "$ x" 2 5
Bcd
# Method 2
# $ {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

Match Regular Expression
Copy codeThe Code is as follows:
# Print matching length
% Expr match $ x "."
1
% Expr match $ x "abc"
3
% Expr match $ x "bc"
0

The beginning and end of a string

Copy codeThe Code is as follows:
% X = aabbaarealwwvvww
% Echo "$ {x % w * w }"
Aabbaarealwwvv
% Echo "$ {x % w * w }"
Aabbaareal
% Echo "$ {x # a * }"
Lwwvvww
% Echo "$ {x # a * }"
Bbaarealwwvvww

Where, # indicates the header, because # on the keyboard is on the left of $.
Here, % indicates % because % on the keyboard is on the right of $.
A single parameter indicates the minimum matching, and a double parameter indicates the maximum matching.
That is to say, when there are multiple matching schemes, select the maximum length or the minimum length of the matching.

String replacement

Copy codeThe Code is as follows:
% X = abcdabcd
% Echo $ {x/a/B} # Replace only one
Bbcdabcd
% Echo $ {x // a/B} # Replace all
Bbcdbbcd

Regexp cannot be used, *? .

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.