What is an internal field separator
Internal field separator (Internal Field Separator, IFS) is an important concept in the shell scripting. Processing
text data, it is no small role.
As a separator, IFS has a special purpose. It is an environment variable, which holds the character used to separate. It is when
the default shell environment delimited string before use. We can see the $ IFS variable, so to see this separator.
[root@dns-node2 tmp]# echo $IFS
Replace the separator thereby slicing string
Consider a situation: we need to iterate through a string type or comma-separated value (Comma Separated Value, CSV)
word. If the former, use IFS = ""; if the latter, using IFS = ",".
[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
The above is not used to do awk specified delimiter, IFS to directly change the slicing string, it badly.
Then take a look at the following example below:
[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
tips
May be used to output echo sequence, for example the following data:
[root@dns-node2 tmp]# echo {1..500}
[root@dns-node2 tmp]# echo {a..z}
[root@dns-node2 tmp]# echo {A..z}