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

版权声明:如若转载,请联系作者。 https://blog.csdn.net/liu16659/article/details/83444332

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.如何使用

  • 代码示例
[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是生效的。

猜你喜欢

转载自blog.csdn.net/liu16659/article/details/83444332