String processing in BASH

Source: Internet
Author: User
Article Title: string processing in BASH. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.

It is transferred from the shell version for my future study. The body is as follows:

Get Length

% 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

% 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

# Method 1

# Expr 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

# Print matching length

% Expr match $ x "."

1

% Expr match $ x "abc"

3

% Expr match $ x "bc"

0

The beginning and end of a string

% 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

% 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.