网站管理员怎么联系,嘉兴市网站建设,建筑行业信息查询平台,wordpress淘宝客教程在linux下一般用while read line与for循环按行读取文件。这两种方法有什么区别呢#xff1f;现有如下test.txt文件#xff1a;1while read linewhile read line; do echo $linedone test.txt输出结果与上图一致。这里也可以写为#xff1a;cat test.txt | while read … 在linux下一般用while read line与for循环按行读取文件。这两种方法有什么区别呢现有如下test.txt文件1while read linewhile read line; do echo $linedone test.txt输出结果与上图一致。这里也可以写为cat test.txt | while read line; do echo $linedone输出结果一致但是需要注意一点就是在如下情况下结果是不同的# 第一种情况while read line; do name1$line;done test.txtecho $name1# 第二种情况cat test.txt | while read line; do name2$linedoneecho $name2在第一种情况下输出ENSMUSG00000000078.7 32.83699 29.78868 38.58607 30.348110000000002第二种情况则无输出。出现这种不同是因为管道的机制这个使用管道之后while read line是在子shell中进行的所以退出之后$name2就没有值了。并且cat 会一次性地把test.txt的所有内容都输入到内存假如文件很大则会占用很大的内存。但是第二种重定向的方法是一行一行的读入更省内存。2for循环for i in cat test.txt;do echo $idone但是输出了这样的结果(部分结果)这是因为在for循环中每次是以空格/制表符为分割符输出。可以写成以下形式输出# 可以先将空格转为别的字符for i in sed s/\t/#/g test.txt;do echo $i | sed s/#/\t/gdone先将空格或者制表符替换为其他字符输出的时候再替换回来即可。