8. shell将字符串以逗号分割转成数组(借助IFS)

原理是将变化shell环境下的一个系统变量IFS

#!/bin/bash

function to_array()

{

x=$1

OLD_IFS="$IFS" #默认的IFS值为换行符

IFS=","

array=($x)  #以逗号进行分割了

IFS="$OLD_IFS" #还原默认换行符

for each in ${array[*]}

do

echo $each

done

}

arr=($(to_array 'a,b,c,d,e'))

echo ${arr[*]}

参考:shell分割字符串为数组


另外一个例子,介绍IFS的用法。参考shell中的特殊变量IFS

比如,有个文件内容如下:

      the first line.

the second line.

the third line.

打印每行:

forline in `cat filename`

do

echo $line

done

结果是下面这种一行一个单词,显然是不符合预期的:

the

first

line.

the

second

line.

the

third

line.


借助IFS变量进行做个调整:

IFS=$'\n'

for line in `cat k.shfile`

do

echo $line

done

输出就是正确的:

    the first line.

the second line.

the third line.

你可能感兴趣的:(8. shell将字符串以逗号分割转成数组(借助IFS))