Shell: 循环单行包含空格的文件
如果直接用【for】循环,你可能会遇到这样的问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
[root@oracle ~]# vi content.txt [root@oracle ~]# [root@oracle ~]# cat content.txt this is a note file. Leviathan The Earth [root@oracle ~]# [root@oracle ~]# for i in $(cat content.txt) > do > echo "==========" > echo "$i" > echo "" > done ========== this ========== is ========== a ========== note ========== file. ========== Leviathan ========== The ========== Earth [root@oracle ~]# |
正确的做法:设置IFS变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[root@oracle ~]# IFS=$'\n' [root@oracle ~]# [root@oracle ~]# for i in $(cat content.txt); do echo "=========="; echo "$i"; echo ""; done ========== this is a note file. ========== Leviathan ========== The Earth [root@oracle ~]# |
可以看到,这时候就曾缺的逐行打印出来了。