在bash中同时从两个文件中读取

时间:2014-06-17 07:14:07

标签: linux bash shell unix

我有两个文件。说f1和f2。

Contents of f1
pointiac
cadillac
mustang

f1和f2不需要具有相同的行数

Contents of f2
black
blue

我的循环读取

cat f2|while read linex
do
<something to read the next line in f1, which in iteration 1 of this loop is the first line, into a variable liney>
#do something with linex and liney
#terminate when all lines in f2 run out, it doesn't matter if there are unprocessed lines in f1
done

我需要的代码允许我在读取f2行的循环中读取f1的下一行。

我理解我的例子有点混乱,难以解释,但我尽了最大努力。我很感激任何帮助。我是一个全新的人物。

1 个答案:

答案 0 :(得分:2)

#! /bin/bash    
while true; do
  read -r lineA <&3
  read -r lineB <&4
  if [ -z "$lineA" -o -z "$lineB" ]; then
    break
  fi
  echo "1: "$lineA
  echo "2: "$lineB
done 3<fileA 4<fileB