Three methods of string segmentation in shell

Source: Internet
Author: User

Question: For string output such as ' 1,2,3,4,5 ', separate 1 2 3 4 5

Feature: no spaces in string

Workaround 1:

#!/bin/bash
var= ' 1,2,3,4,5 '
var=${var//,/}    #这里是将var中的, replace with space for
element in $var 
do
    echo $ Element done


If there is a space in the original string such as a string such as ' Mark:x:0:0:this is a test user:/var/mark:nologin ', to output the string as delimited, the method above will output the This is a test user separately, which is not correct.

Workaround 2 for this situation:

#!/bin/bash
user= ' mark:x:0:0:this is a test user:/var/mark:nologin ' for
((i=1;i<=7;i++) does
        echo $user |cut-d ":"-f$i done


The above method is to determine the length of the string separated, if the write more general point, to the following

Workaround 3:



#!/bin/bash
user= ' mark:x:0:0:this is a test user:/var/mark:nologin '
i=1 while
((1==1))
do
        split = ' echo $user |cut-d ': '-f$i '
        if [$split '!= ']
        then
                ((i++))
                echo $split else break
        fi Done

This method does not need to know the number of separated strings, and has a better versatility.

Related Article

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.