Korn Shell中IFS的妙用

IFS是internal field separator的缩写,shell的特殊环境变量。ksh根据IFS存储的值,可以是空格、tab、换行符或者其他自定义符号,来解析输入和输出的变量值。

 

如果有一IP地址220.112.253.111, 欲将这个IP地址颠倒顺序,你可以定义IFS为".",然后直接echo这个地址即可得到此IP的4个数值,然后c重新把IFS设为空格,重新组合四个IP地址的数值即可。

 

 

更详细的IFS的介绍参见下文:(原文地址:http://www.livefirelabs.com/unix_tip_trick_shell_script/oct_2003/10132003.htm

 

Another shell variable that you should become comfortable using is the IFS, or internal field separator, variable.  The shell uses the value stored in IFS, which is the space, tab, and newline characters by default, to delimit words for the read and set commands, when parsing output from command substitution, and when performing variable substitution.

IFS can be redefined to parse one or more lines of data whose fields are not delimited by the default white-space characters.  Consider this sequence of variable assignments and for loops:

$ line=learn:unix:at:livefire:labs
$ for i in $line
> do
> echo $i
> done
learn:unix:at:livefire:labs
$ OIFS=$IFS
$ IFS=:
$ for i in $line
> do
> echo $i
> done
learn
unix
at
livefire
labs
$

The first command assigns the string “learn:unix:at:livefire:labs” to the variable named line.  You can see from the first for loop that the shell treats the entire string as a single field.  This is because the string does not contain a space, tab, or newline character. 

After redefining IFS, the second for loop treats the string as four separated fields, each delimited by a colon.  Using a colon for IFS would be appropriate when parsing the fields in a record from /etc/passwd, the user account information file:

livefire:x:100:1::/export/home/livefire:/bin/ksh

Notice that the original value of IFS was stored in OIFS (“O” for original) prior to changing its value.  After you are finished using the new definition, it would be wise to return it to its original value to avoid unexpected side effects that may surface later on in your script. 

TIP – The current value of IFS may be viewed using the following pipeline:

$ echo "$IFS" | od -b
0000000 040 011 012 012
0000004
$

The output of the echo command is piped into the octal dump command, giving you its octal equivalent.  You can then use an ASCII table to determine what characters are stored in the variable.  Hint: Ignore the first set of zeros and the second newline character (012), which was generated by echo.

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值