linux数组拼接_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[*]}

另外一个例子,介绍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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值