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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容