2012-10-12日更新此博客,增加对含有空格的行的遍历。
1. 可以使用while readi
cat d.txt | while read i;do echo $i; done
while read i; do echo $i; done < d.txt
2. 文件遍历:
一个目录下如果有含有空格或者其他特殊字符的文件,如何在bash中循环他们呢?我们知道在bash的循环中,是使用空格作为元素的分界符的,即便 文件加上引号,依旧不能正确指定完整的文件为元素(如果文件名含有空格的话).
例如:
#如果文件含有空格,则会根据空格把文件名拆分! for file in $(ls -Q ./src/); do echo $file; done
即便把文件名作为脚本的参数,然后在参数名上加上引号,也不能成功,例如:
#Script Name: mysccript #在脚本后加上文件名,并以引号括起来 for file in $@; do echo $file; done 执行: ./myscript "fname 1" "fname 2" 结果: fname 1 fname 2
这里我们使用一种方法: for file in ../*; do echo $file; done,
3. 即在in中直接指定路目地址并加上星号指定所有的文件.或者利用通配符指定一系列文件例如:fname*.例如:
for file in ./fname*; do echo $file; done
4. ./*不能够遍历到隐性文件,如果只要遍历隐性文件则使用 ./.* 。如果要遍历到所有的文件(包括隐性文件),则要借助ls -A 和 while read。
[root@localhost ~]# for i in ./.*;do echo $i;done ./. ./.. ./.bash_history ./.bash_logout ./.bash_profile ./.bashrc ./.cshrc ./.dbshell ./.lesshst ./.mongorc.js ./.tcshrc ./.viminfo
[root@localhost ~]# ls -A ./|while read i;do echo $i;done a b anaconda-ks.cfg .bash_history .bash_logout .bash_profile .bashrc .cshrc .dbshell grub.conf install.log install.log.syslog .lesshst .mongorc.js nohup.out Python2.7 Python-2.7.3 Python-2.7.3.tar.bz2.tar.bz2.tar.bz2 scripts sedlfz71t .tcshrc test test2 .viminfo