内部字段分隔符(Internal Field Separator,IFS)是shell脚本编程中的一个重要概念。在处理
文本数据时,它的做用可不小。
做为分隔符,IFS有其特殊用途。它是一个环境变量,其中保存了用于分隔的字符。它是当
前shell环境使用的默认定界字符串。咱们能够查看$IFS这个变量,从而看出这个分隔符。node
[root@dns-node2 tmp]# echo $IFS
考虑一种情形:咱们须要迭代一个字符串或逗号分隔型数值(Comma Separated Value,CSV)
中的单词。若是是前者,可使用 IFS=" " ;若是是后者,则使用 IFS="," 。shell
[root@dns-node2 tmp]# cat testIFS.sh #!/bin/bash data="name,age,sex,telphone_number,location" oldIFS=$IFS IFS=, for i in $data do echo item: $i done IFS=$oldIFS [root@dns-node2 tmp]# sh testIFS.sh item: name item: age item: sex item: telphone_number item: location
以上就是没有使用awk来作指定分隔符,直接更改IFS来切分字符串,厉害吧。
接下来看看下面下面例子:编程
[root@dns-node2 tmp]# cat testIFS2.sh #!/bin/bash line="root:x:0:0:root:/root:/bin/bash" IFS=":" for i in $line do echo $i done [root@dns-node2 tmp]# bash testIFS2.sh root x 0 0 root /root /bin/bash
可使用echo 来输出序列,例以下面的数据:bash
[root@dns-node2 tmp]# echo {1..500} [root@dns-node2 tmp]# echo {a..z} [root@dns-node2 tmp]# echo {A..z}