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
- #!/bin/bash
- Var= ' 1,2,3,4,5 '
- var=${var//,/} #这里是将var中的, replace with a space
- for element in $var
- Do
- Echo $element
- 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
- #!/bin/bash
- User= ' Mark:x:0:0:this is a test user:/var/mark:nologin '
- For ((i=1;i<=7;i++))
- Do
- echo $user |cut-d ":"-f$i
- 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
- #!/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, with better versatility
Three ways to split a string in a shell