Chinaunix

标题: for循环分隔符问题 [打印本页]

作者: 风吹不倒    时间: 2010-02-25 16:02
标题: for循环分隔符问题
file如下
----------------------------
server1 ip1 password1
server2 ip2 password2
server3 ip3 password3

-----------------------------
用for循环将每一行提出来,命令如下:
for i in `cat file`;do echo $i;done

本想每次得到server1 ip1 password1
但事实上却给了我
server1
ip1
password1

我想问如何让for循环不以空格(或tab)为分隔符,而以换行符为分隔。

用别的特殊字符代替空格的方法最近在用,但password一变更,又得找个密码中没有的特殊字符做分隔,很麻烦,还得碰运气。 求个好法子!
作者: wqfhenanxc    时间: 2010-02-25 16:09
回复 1# 风吹不倒


    OLDIFS=$IFS;IFS='\n';for i in `cat test`;do echo $i;done;IFS=$OLDIFS
作者: 风吹不倒    时间: 2010-02-25 16:12
回复 2# wqfhenanxc


    非常感谢,清晰明朗!
作者: blackold    时间: 2010-02-25 16:44
可以用'\n'? 用的哪种shell?
作者: angle4    时间: 2010-02-25 16:52
sh, bash 都行
作者: wqfhenanxc    时间: 2010-02-25 16:55
回复 4# blackold


$ bash --version
GNU bash, version 3.2.39(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.
作者: blackold    时间: 2010-02-25 16:56
回复 5# angle4


    应该说都不行。表面上看起来行了。
作者: 风吹不倒    时间: 2010-02-25 17:03
本帖最后由 风吹不倒 于 2010-02-25 17:06 编辑

额 用了wqfhenanxc的方法后,for循环里echo $i达到了预期想要的;而我在循环里的函数执行了一次,就退出了。不能理解...


函数里又以空格为分隔符,将三段都取出。
作者: goride    时间: 2010-02-25 17:05
黑哥,讲讲
作者: blackold    时间: 2010-02-25 17:15
本帖最后由 blackold 于 2010-02-25 17:29 编辑

晕,放入code后变样了,修改为quote。

$ echo $0
bash

$ echo -En '\n'|xxd
0000000: 5c6e                                     \n

$ (IFS='\n';for i in $(<urfile);do echo i:;done)
:server1 ip1 password1
server2 ip2 password2
server3 ip3 password3:

$ echo -En $'\n'|xxd
0000000: 0a                                       .

$ (IFS=$'\n';for i in $(<urfile);do echo i:;done)
:server1 ip1 password1:
:server2 ip2 password2:
:server3 ip3 password3:

作者: wqfhenanxc    时间: 2010-02-25 17:22
回复 8# 风吹不倒


    那大概是因为在循环中你执行的命令用到了IFS,而此时的IFS还是'\n';
解决方法:
OLDIFS=$IFS
IFS='\n'
for i in `cat ufile`
do
IFS=$OLDIFS
your command
IFS='\n'
done
IFS=$OLDIFS

不过这个看起来真的很愚笨,还请黑哥解释深层含义并支招吧。。
作者: 风吹不倒    时间: 2010-02-25 17:40
回复 10# blackold


    参照黑哥的quota解决问题了!IFS=$'\n'是准确的
作者: 风吹不倒    时间: 2010-02-25 17:42
回复 11# wqfhenanxc


    IFS='\n',感觉象是直接读最后的换行符了,表现为只循环了一次
作者: wqfhenanxc    时间: 2010-02-25 17:48
回复 13# 风吹不倒


    恩,试了下,我在11#中的方法还是不行,高手跟低手还是差距呀!
作者: blackold    时间: 2010-02-25 17:50
回复 14# wqfhenanxc


    我也不是什么高手,只是比你多看了几页书。
作者: 风吹不倒    时间: 2010-02-25 17:51
...... 我提的问题也不错
作者: blackold    时间: 2010-02-25 17:53
回复 16# 风吹不倒


    老问题了,本版有一大箩。
作者: wqfhenanxc    时间: 2010-02-25 17:58
回复 17# blackold


    黑哥能不能给解释下$'\n'是什么意思?
为啥加个$就能把\n给解释成换行符了?
作者: blackold    时间: 2010-02-25 18:03
回复 18# wqfhenanxc


    bash按照ANSI C来解释$'string'中的string。
作者: 網中人    时间: 2010-02-26 02:48
如果是從文件讀入,丟給 while read line 也行




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2