Linux命令详解之字符串分割&&IFS

Linux命令详解之字符串分割&&IFS

1.IFS是什么

IFS是Linux系统中默认的环境变量。指的是:interval field separator

**The internal field separator (IFS) is an important concept in shell scripting. It is very useful
while manipulating text data. … An internal field separator is a delimiter for a special
purpose. An internal field separator is an environment variable that stores delimiting
characters. It is the default delimiter string used by a running shell environment.
Consider the case where we need to iterate through words in a string or comma separated
values (CSV). In the first case we will use IFS=" " and in the second, IFS=",".【译:在第一种情况(默认)下,IFS的值是空格;在第二种情况下,我们就需要使用,作为分隔符】 **

2.如何使用
2.1 IFS作为分割符(变量替换)
[root@server4 shells]# cat test10.sh
#!/bin/bash
data="name,sex,location"
oldIFS=$IFS
IFS=,
for item in $data
do
 echo item: $item
done

data1="my name is Lawson could you be my fans?"
for i in $data1
do
 echo i: $i
done

IFS=$oldIFS

执行结果如下:

[root@server4 shells]# ./test10.sh 
item: name
item: sex
item: location
i: my name is Lawson could you be my fans?

可以看到在代码的前半部分,我们定义IFS=,作为分隔符,接着在for循环中,将其输出**【但是我很好奇,为什么,这里就会将其作为一个类似于C语言中的数组,并且输出呢?】**。
为了证明不使用IFS这个变量是否可以同样输出字符串,我在脚本的后半部分,又写了如下代码

data1="my name is Lawson could you be my fans?"
for i in $data1
do
 echo i: $i
done

但是这段代码的执行结果却是将data1作为了一个整体的字符串全部输出了。证明了IFS是生效的。

3. 注意事项

IFS 只支持使用一个字符进行分割字符串,而不支持使用一个字符串分割字符串。 示例如下:

[root@server4 shells]# cat dealWithString.sh 
#!/bin/bash
param=$1

# the first param
echo =======before=====
echo original string :$param

echo =======after=====
#replace the IFS
oldIFS=$IFS
IFS='sparkhdop'

length=${#param[@]}
echo length of arr: $length

for item in $param
do
 echo item: $item
done

IFS=$oldIFS

执行结果如下:
在这里插入图片描述
可以看到,这里使用了IFS='sparkhdop',即IFS使用这个字符串中的任一字符作为分隔符。而不是sparkhdop字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

说文科技

看书人不妨赏个酒钱?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值