Three ways to split a string in a shell

Source: Internet
Author: User

Problem: String output of ' 1,2,3,4,5 ' is used, separated by 1 2 3 4 5

Feature: There are no spaces in the string

Workaround 1:

[Plain]View Plaincopy
    1. #!/bin/bash
    2. Var= ' 1,2,3,4,5 '
    3. var=${var//,/} #这里是将var中的, replace with a space
    4. for element in $var
    5. Do
    6. Echo $element
    7. Done



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

For this scenario, workaround 2:

[Plain]View Plaincopy
    1. #!/bin/bash
    2. User= ' Mark:x:0:0:this is a test user:/var/mark:nologin '
    3. For ((i=1;i<=7;i++))
    4. Do
    5. echo $user |cut-d ":"-f$i
    6. Done



The above method is to determine the length of the string after the separation, if the writing is more general, to the following

Workaround 3:

[Plain]View Plaincopy
  1. #!/bin/bash
  2. User= ' Mark:x:0:0:this is a test user:/var/mark:nologin '
  3. I=1
  4. while ((1==1))
  5. Do
  6. Split= ' echo $user |cut-d ': '-f$i '
  7. If ["$split"! = ""]
  8. Then
  9. ((i++))
  10. Echo $split
  11. Else
  12. Break
  13. Fi
  14. Done

This method does not need to know the number of separated strings, with better versatility

Three ways to split a string in a shell

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.