手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

如何用Shell逐行读取文件

[日期:2012-04-19] 来源:Linux社区  作者:liangliyin [字体:大 中 小]

在学习Linux shell scripts时,一个最常见的错误就是用for(for line in $(cat file.txt) do …)循环逐行读取文件。下面的例子可以看出这样做的结果。

文件file.txt内容:

cat file.txt

This is the row No 1;

This is the row No 2;

This is the row No 3.

 

用for循环的例子:

for line in $(cat file.txt); do echo $line; done

This

is

the

row

No

1;

This

is

the

row

No

2;

[…]

显然这并不是我们想要的效果。解决方案是采用带内部读取的while循环。

while循环是用来逐行读取文件最恰当且最简单的方法:

while read line; do echo $line; done < file.txt

This is the row No 1;

This is the row No 2;

This is the row No 3.

linux
相关资讯       Linux Shell 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款