shell下同时读取多个文件的方法

来源:互联网 发布:佩里西奇 数据 编辑:程序博客网 时间:2024/05/15 00:25

1. 单个文件的读取

在shell脚本下,可以多种方式实现按行读取文件,如下:

for line in `cat ${input_filename}`do  echo $linedone
while read linedo  echo $linedone < ${input_filename}

其中第二种方式是将文件重定向到标准输入中

2. 多个文件读取方法

那如何实现同时多个文件的读呢?
我们可以继续利用bash中的文件重定向功能,将文件重定向到特定的文件描述符中,语法如下:

n<filen>filen>>filen<>file

这里的n代表打开文件file的文件描述符,类似其他编程语言中的fd,如果没有指定n,则其默认行为如下:

<file   #same as 0<file>file  #same as 1>file<>file   #same as 0<>file

我们可以通过exec命令来打开所要重定向的文件:

exec 7<file1exec 8<file2

然后我们可以通过read命令来读取对应文件的内容:

read data <&7 #使用符合是为了区分7是文件描述符,而不是文件名read data <&8
关闭文件
exec 7</dev/nullexec 8</dev/null

多文件读取示例代码如下:

readfiles() {local FD1=7local FD2=8local file1=$1local file2=$2local count1=0local count2=0local eof1=0local eof2=0local data1local data2 # Open files.exec 7<$file1exec 8<$file2while [[ $eof1 -eq 0  ||  $eof2 -eq 0 ]]doif read data1<&$FD1; thenlet count1++printf "%s, line %d: %s\n" $file1 $count1 "$data1"elseeof1=1fiif read data2 <&$FD2; thenlet count2++printf "%s, line %d: %s\n" $file2 $count2 "$data2"elseeof2=1fidone}#read file1 and file2readfiles file1 file2转载自:http://www.jb51.net/LINUXjishu/62836.html