在bash中获取文件指针并任意读取行

zyl*_*024 1 linux io bash file-io

我有一个 bash 脚本,需要在其中逐行读取文件。我知道通常的工作原理while read line,但我的程序不能很好地适应循环while。我有两个文件,需要在某些条件下逐行比较它们(不是diff:条件是一个文件中的行是否以另一个文件中的行开头)。目前我有一个Java版本的程序,它有三个嵌套循环,两个文件的循环交织在一起,我需要打破嵌套循环(我知道怎么做)。所以我想要一个优雅的解决方案来在 bash 中执行以下基本任务(以下代码是我的 Java 程序):

BufferedReader reader = new BufferedReader(new FileReader(inputFile)); // initialize a file pointer
reader.ready();                                                        // whether the pointer is at the end of the file (used in while and if conditions)
lineStr = reader.readLine();                                           // read next line
Run Code Online (Sandbox Code Playgroud)

我在网上找到的所有解决方案都使用规范while read line结构,但我的程序无法适应它。所以我想以更多的控制来操作文件。

kon*_*box 5

要在循环中逐行比较两个文件,您可以简单地执行以下操作:

while read -u 4 A && read -u 5 B; do
    <do something with $A and $B>
done 4< file1.txt 5< file2.txt
Run Code Online (Sandbox Code Playgroud)

或者

for (( ;; )); do
    read -u 4 A || {
        <read error/eof; perhaps you can send a message here and/or break the loop with break>
    }
    read -u 5 B || {
        <do something similar>
    }
    <do something with $A and $B>
done 4< file1.txt 5< file2.txt
Run Code Online (Sandbox Code Playgroud)