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.