用bash脚本读文件的方法有很多。请看第一部分,我使用了while循环及其后的管道命令(|)(cat $FILE | while read line; do … ),并在循环当中递增 i 的值,最后,我得到了非我所想的 i 。主要的原因是,管道命令会发起子shell来读取文件,而任何在(子shell的)while循环中的操作(例如 i ++),都会随着子shell的结束而丢失。

而第二种,也是最坏的一种,其最明显的错误就是在读文件的过程中使用了for循环(for fileline in $(cat $FILE);do ..),这样每打印一个单词就换一次行,因为for循环使用空格作为默认的IFS。

完美的方法,即第三种的while循环(while read line;do …. done < $FILE) 是最合适且最简单的一行行地读文件的方法。请看以下例子。

Input: $ cat sample.txt
This is sample file
This is normal text file Source: $ cat readfile.sh
#!/bin/bash i=1;
FILE=sample.txt # Wrong way to read the file.
# This may cause problem, check the value of 'i' at the end of the loop
echo "###############################"
cat $FILE | while read line; do
echo "Line # $i: $line"
((i++))
done
echo "Total number of lines in file: $i" # The worst way to read file.
echo "###############################"
for fileline in $(cat $FILE);do
echo $fileline
done # This is correct way to read file.
echo "################################"
k=1
while read line;do
echo "Line # $k: $line"
((k++))
done < $FILE
echo "Total number of lines in file: $k" Output: $ ./readfile.sh
###############################
Line
# 1: This is sample file
Line
# 2: This is normal text file
Total number of lines in file: 1
###############################
This
is
sample
file
This
is
normal
text
file
################################
Line
# 1: This is sample file
Line
# 2: This is normal text file
Total number of lines in file: 3

  

最新文章

  1. Java基础知识点4:继承
  2. 【精粹系列】PHP精粹
  3. 编写一个简单的jdbc例子程序
  4. [WebServer] Windows操作系统下 Tomcat 服务器运行 PHP 的环境配置
  5. SQL注入截取字符串函数
  6. 微信公众号红包接口开发PHP开发 CA证书出错,请登陆微信支付商户平台下载证书
  7. 大数据时代的IT架构设计
  8. PagerHelper-分页类
  9. Linux 学习手记(4):Linux系统常用Shell命令
  10. linux 安装
  11. React如何性能调优
  12. JavaScript 客户端JavaScript之 脚本化浏览器窗口
  13. string 转换char类型
  14. Poj 2371 Questions and answers(排序)
  15. lumen框架
  16. Mybatis源码分析-StatementHandler
  17. 数据处理不等式:Data Processing Inequality
  18. leetcode python最长回文子串
  19. 【MySql】删除操作
  20. Visual Studio 2015开发Qt项目实战经验分享(附项目示例源码)

热门文章

  1. euclidean loss
  2. Android学习笔记_6_保存文件到SDCard
  3. EF6.0 对于数据库优 模式 新加功能
  4. 7.Vue-Quill-Editor图片插入自定义
  5. 菜鸟笔记 -- Chapter 6.3&#160;对象
  6. 9.异常Exception
  7. [oracle]分区表学习
  8. Python基础—16-网络编程
  9. Hibernate知识点小结(四)--JPA
  10. 洛谷P1196 [NOI2002]银河英雄传说(带权并查集)