查看: 1062|回覆: 0

[教程] shell下同时读取多个文件的方法

[複製鏈接]

8

主題

0

回帖

24

積分

技术1级

金币
16
閲讀權限
10
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2010-12-8
QQ
發表於 2009-5-4 03:27:02 | 顯示全部樓層 |閲讀模式
                        1. 单个文件的读取

            在shell脚本下,可以多种方式实现按行读取文件,如下:
                                   
  1. for line in `cat ${input_filename}`
  2. do
  3.   echo $line
  4. done
複製代碼
                                                         
  1. while read line
  2. do
  3.   echo $line
  4. done < ${input_filename}
複製代碼
                                   其中第二种方式是将文件重定向到标准输入中
            2. 多个文件读取方法

            那如何实现同时多个文件的读呢?
我们可以继续利用bash中的文件重定向功能,将文件重定向到特定的文件描述符中,语法如下:
                                   
  1. n<file
  2. n>file
  3. n>>file
  4. n<>file
複製代碼
                                   这里的n代表打开文件file的文件描述符,类似其他编程语言中的fd,如果没有指定n,则其默认行为如下:
                                   
  1. <file   #same as 0<file
  2. >file  #same as 1>file
  3. <>file   #same as 0<>file
複製代碼
                                   我们可以通过exec命令来打开所要重定向的文件:
                                   
  1. exec 7<file1
  2. exec 8<file2
複製代碼
                                   然后我们可以通过read命令来读取对应文件的内容:
                                   
  1. read data <&7 #使用符合是为了区分7是文件描述符,而不是文件名
  2. read data <&8
複製代碼
                                   关闭文件

                                   
  1. exec 7</dev/null
  2. exec 8</dev/null
複製代碼
                                   多文件读取示例代码如下:
                                   
  1. readfiles() {
  2.         local FD1=7
  3.         local FD2=8
  4.         local file1=$1
  5.         local file2=$2
  6.         local count1=0
  7.         local count2=0
  8.         local eof1=0
  9.         local eof2=0
  10.         local data1
  11.         local data2

  12.         # Open files.
  13.         exec 7<$file1
  14.         exec 8<$file2
  15.         while [[ $eof1 -eq 0  ||  $eof2 -eq 0 ]]
  16.         do
  17.                 if read data1<&$FD1; then
  18.                         let count1++
  19.                         printf "%s, line %d: %s\n" $file1 $count1 "$data1"
  20.                 else
  21.                         eof1=1
  22.                 fi
  23.                 if read data2 <&$FD2; then
  24.                         let count2++
  25.                         printf "%s, line %d: %s\n" $file2 $count2 "$data2"
  26.                 else
  27.                         eof2=1
  28.                 fi
  29.         done
  30. }
  31. #read file1 and file2
  32. readfiles file1 file2
複製代碼
                                   
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部