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
字符串。