Shell string segmentation

Source: Internet
Author: User
Entry Level

Entry level: strings like 1, 2, 3, 4, and 5

#! /Bin/bashvar = "1, 2, 3, 4, 5" Var =$ {var //,/} For I in $ var; do echo $ I; done

In this way, the results can be output.

Shap level

In the preceding example, the split string cannot contain spaces, for example, ", 9 ,".

#! /Bin/bashvar = "1, 2, 3, 4 9, 5" for (I = 1; I <= 4; I ++) do echo $ var | cut-d ", "-F $ idone

Here we will explain the small part of cut, which is similar to awk. The-D parameter is a separator and the-F parameter specifies the position.

Depth level

The disadvantage of the above example is that we need to calculate the number of "," in advance.

#! /Bin/bashvar = "1, 2, 3, 4 9, 5" I = 1 while (1 = 1); Do TMP = 'echo $ var | cut-d ", "-F $ I 'If [" $ tmp "=" "]; then break; else echo $ TMP; (I ++) fidone

This method is more complex, but more universal.

Shell string segmentation

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.