String operations in bash

Source: Internet
Author: User
Technorati tags: String, Bash, expr

Search for the length of the substring expr match "string" 'string '. Here, the substring is a regular expression. For example, if expr match "abcdefg123456" '[A-Z] * [0-9]', 8 is returned. The regular expression [A-Z] * [0-9] matches abcdefg1, so the length is 8.

Extract the substring expr substr string POS Len. This is equivalent to substr () in STD: string of C ++ (). The difference is that the subscript of POS starts from 1, and the subscript of STD: String starts from 0. For example, expr substr "abcdefg123456" 1 6, the extracted substring is abcdef, starting from the first one with a length of 6.

In fact, the string operation functions in bash are rich and diverse. For example, the length of the substring is written in another way: expr "$ string": '$ substring '. The extracted substrings are also $ {string: Position} and $ {string: Position: length. These different forms of string operations are both convenient and confusing. In advanced bash scripting guide, it is called "bash supports a surprising number of string manipulation operations. unfortunately, these tools lack a uniied focus. some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr command. this results in inconsistent command syntax and overlap of functionality, not to mention confusion."

The following code copies all *. PNG files in the current state of ABC123 to a new place and uses ABC as the directory. Here ''is the key on the tab, which represents the expression value. It can be used to assign the return value in'' to the variable.

1: For a in $ (ls $ srcdir)
2: Do
3: Len = 'expr match "$ A" '[A-Z] * [0-9]''
4: Len = $ ($ len-1 ))
5: Echo $ Len
6: B = 'expr substr $ A 1 $ len'
7: Echo $ A to $ B
8: mkdir-p $ dstdir/$ B
9: CP $ srcdir/$ A/maps/*. PNG $ dstdir/$ B/
10: Done

Ref: http://tldp.org/LDP/abs/html/string-manipulation.html

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.